Get the latest angular interview questions and answers. Below are list of 200+ angular interview q & a. which must be prepared before going for a front end developer interview.

Angular interview questions is the hottest coding skills in the 2021. A report says that in 2021-22 Angular will create more jobs than any other front end framework. As supported and owned by google. It will grow forever and create opportunity for beginners as well as experience developers.

If you are aspiring front end candidate and looking to change for high paying job, then you should prepare the below Frequently asked Angular questions and answers first. This Top Angular interview questions is must before appearing for an technical front end interview. Also you can check the employers requirement and prepare accordingly.

Q1. What is Angular?

Ans: Angular is a platform and framework for building single-page client applications using HTML and TypeScript. Angular is written in TypeScript. It implements core and optional functionality as a set of TypeScript libraries that you import into your apps.

Platform that makes it easy to build applications with in web/mobile/desktop. The major features of this framework such as declarative templates, dependency injection, end to end tooling, and many more other features are used to ease the development.

Q2. What is the difference between AngularJS and Angular?

Ans: Angular 2+ is completely different from the initial version angular.JS or version 1. main difference are

AngularJSAngular
It is based on MVC architectureThis is based on Service/Components
This uses use JavaScript to build the applicationtypescript to write the application.
RXJS introduced.
No reactiveReactive programming
Controller basedComponent based
Not a mobile friendly
mobile First

Not SEO friendlySEO friendly
speed slowSpeed improvement by change detection mechanism
AngularJS vs Angular

Q3. What is TypeScript?

Ans: TypeScript is a typed superset of JavaScript created by Microsoft that adds optional types, classes, async/await, and many other features, and compiles to plain JavaScript. Angular built entirely in TypeScript and used as a primary language. You can install it globally as

> npm install -g typescript

Example of typescript usage

function hello(person: string) {
    return "Hello, " + person;
}

let user = "Seoinfotech";

document.body.innerHTML = hello(user);
//The hello method allows only string type as argument.

Q4. Write a pictorial diagram of Angular architecture?

Ans: Diagram of the angular architecture is

Source: angular.io

Q5. What are the key components of Angular?

Ans: Angular has key components as below.

  1. Component: These are the basic building blocks of angular application to control HTML views.
  2. Modules: An angular module is set of angular basic building blocks like component, directives, services etc. An application is divided into logical pieces and each piece of code is called as “module” which perform a single task.
  3. Templates: This represent the views of an Angular application.
  4. Services: It is used to create components which can be shared across the entire application.
  5. Metadata: This can be used to add more data to an Angular class.

Q6. What are directives?

Ans: A directive is a class with @Directive decorator. Directives add behavior to an existing DOM element or an existing component instance.

There are 2 types of directive.

  1. Structural Directives like *ngIf, *ngFor etc
  2. Attribute Directive like [(ngModel)] = “hero.name”
// Example of attribute directive
import { Directive, ElementRef, Input } from '@angular/core';

@Directive({ selector: '[myHighlight]' })
export class HighlightDirective {
    constructor(el: ElementRef) {
       el.nativeElement.style.backgroundColor = 'yellow';
    }
}

Now this directive extends HTML element behavior with a yellow background as below

<p myHighlight>Highlight me!</p>

Q7. What are components?

Ans: Components are the most basic UI building block of an Angular app which formed a tree of Angular components. These components are subset of directives. Unlike directives, components always have a template and only one component can be instantiated per an element in a template. Let’s see a simple example of Angular component

import { Component } from '@angular/core';

@Component ({
   selector: 'my-app',
   template: ` <div>
      <h1>{{title}}</h1>
      <div>First component</div>
   </div> `,
})

export class AppComponent {
   title: string = 'Welcome to First component';
}

Q8. What are the differences between Component and Directive?

Ans: Components have their own view (HTML and styles). Directives are just “behavior” added to existing elements and components.

Component Directive
To register a component we use @Component meta-data annotation (decorator)To register directives we use @Directive meta-data annotation
Components are typically used to create UI widgets
Directive is used to add behavior to an existing DOM element
Component is used to break up the application into smaller componentsDirective is use to design re-usable components

Only one component can be present per DOM element
Many directives can be used per DOM element

@View decorator or templateurl/template are mandatory
Directive doesn’t use View

Q9. What is a template?

Ans: A template is a HTML view where you can display data by binding controls to properties of an Angular component. You can store your component’s template in one of two places. You can define it inline using the template property, or you can define the template in a separate HTML file and link to it in the component metadata using the @Component decorator’s templateUrl property.

//example of inline template
import { Component } from '@angular/core';

@Component ({
   selector: 'my-app',
   template: '
      <div>
         <h1>{{title}}</h1>
         <div>Learn Angular</div>
      </div>
   '
})

export class AppComponent {
   title: string = 'Hello World';
}
//using separate template  file.
import { Component } from '@angular/core';

@Component ({
   selector: 'my-app',
   templateUrl: 'app/app.component.html'
})

export class AppComponent {
   title: string = 'Hello World';
}

Q10. What is a module?

Ans: Modules are logical boundaries in your application and the application is divided into separate modules to separate the functionality of your application. Lets take an example of app.module.ts root module declared with @NgModule decorator as below.

import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent }  from './app.component';

@NgModule ({
   imports:      [ BrowserModule ],
   declarations: [ AppComponent ],
   bootstrap:    [ AppComponent ],
   providers: []
})
export class AppModule { }

The NgModule decorator has five important(among all) options

  1. The imports option is used to import other dependent modules. The BrowserModule is required by default for any web based angular application
  2. The declarations option is used to define components in the respective module
  3. The bootstrap option tells Angular which Component to bootstrap in the application
  4. The providers option is used to configure set of injectable objects that are available in the injector of this module.
  5. The entryComponents option is a set of components dynamically loaded into the view.

Q11. What are lifecycle hooks available?

Ans: Angular application goes through an entire set of processes or has a lifecycle right from its initiation to the end of the application. The representation of lifecycle in pictorial representation as follows.

angular lifecycle
  • ngOnChanges: Called before ngOnInit() and whenever one or more data-bound input properties change. Note that if your component has no inputs or you use it without providing any inputs, the framework will not call ngOnChanges().
  • ngOnInit: Called once, after the first ngOnChanges()
  • ngDoCheck: Detect and act upon changes that Angular can’t or won’t detect on its own. Called immediately after ngOnChanges() on every change detection run, and immediately after ngOnInit() on the first run.
  • ngAfterContentInit: Respond after Angular projects external content into the component’s view, or into the view that a directive is in. Called once after the first ngDoCheck().
  • ngAfterContentChecked: Respond after Angular checks the content projected into the directive or component. Called after ngAfterContentInit() and every subsequent ngDoCheck().
  • ngAfterViewInit: Respond after Angular initializes the component’s views and child views, or the view that contains the directive. Called once after the first ngAfterContentChecked().
  • ngAfterViewChecked: Respond after Angular checks the component’s views and child views, or the view that contains the directive. Called after the ngAfterViewInit() and every subsequent ngAfterContentChecked()
  • ngOnDestroy: Cleanup just before Angular destroys the directive or component. Unsubscribe Observables and detach event handlers to avoid memory leaks. Called immediately before Angular destroys the directive or component.

Q12. What is a data binding?

Ans: Data binding is a core concept in Angular and allows to define communication between a component and the DOM, making it very easy to define interactive applications without worrying about pushing and pulling data. There are four forms of data binding(divided as 3 categories) which differ in the way the data is flowing.

1. From the Component to the DOM:
Interpolation: {{ value }}: Adds the value of a property from the component.

<li>Name: {{ user.name }}</li>
<li>Address: {{ user.address }}</li>

Property binding: [property]=”value”: The value is passed from the component to the specified property or simple HTML attribute.

<input type="email" [value]="user.email">

2. From the DOM to the Component: Event binding: (event)=”function”: When a specific DOM event happens (eg.: click, change, keyup), call the specified method in the component.

<button (click)="logout()"></button>

3. Two-way binding: Two-way data binding: [(ngModel)]=”value”: Two-way data binding allows to have the data flow both ways. For example, in the below code snippet, both the email DOM input and component email property are in sync.

<input type="email" [(ngModel)]="user.email">

Q13. What is metadata?

Ans: Metadata is used to decorate a class so that it can configure the expected behavior of the class. The metadata is represented by decorators

  1. Class decorators, e.g. @Component and @NgModule
import { NgModule, Component } from '@angular/core';

@Component({
  selector: 'my-component',
  template: '<div>Class decorator</div>',
})
export class MyComponent {
  constructor() {
    console.log('CLASS DECORATOR');
  }
}

@NgModule({
  imports: [],
  declarations: [],
})
export class MyModule {
  constructor() {
    console.log('Hey I am a module!');
  }
}

2. Property decorators Used for properties inside classes, e.g. @Input and @Output

import { Component, Input } from '@angular/core';

@Component({
    selector: 'my-component',
    template: '<div>Property decorator</div>'
})

export class MyComponent {
    @Input()
    title: string;
}

3. Method decorators Used for methods inside classes, e.g. @HostListener

import { Component, HostListener } from '@angular/core';

@Component({
    selector: 'my-component',
    template: '<div>Method decorator</div>'
})
export class MyComponent {
    @HostListener('click', ['$event'])
    onHostClick(event: Event) {
        // clicked, `event` available
    }
}

4. Parameter decorators Used for parameters inside class constructors, e.g. @Inject, Optional

import { Component, Inject } from '@angular/core';
import { MyService } from './my-service';

@Component({
    selector: 'my-component',
    template: '<div>Parameter decorator</div>'
})
export class MyComponent {
    constructor(@Inject(MyService) myService) {
        console.log(myService); // MyService
    }
}

Q14. What is Angular CLI?

Ans: Angular CLI(Command Line Interface) is a command line interface to scaffold and build angular apps using nodejs style (commonJs) modules. You need to install using below npm command.

npm install @angular/cli@latest
  • ng generate class my-new-class: add a class to your application
  • ng generate component my-new-component: add a component to your application
  • ng generate directive my-new-directive: add a directive to your application
  • ng generate enum my-new-enum: add an enum to your application
  • ng generate module my-new-module: add a module to your application
  • ng generate pipe my-new-pipe: add a pipe to your application
  • ng generate service my-new-service: add a service to your application
  1. Creating New Project: ng new
  2. Generating Components, Directives & Services: ng generate/g The different types of commands would be

3. Running the Project: ng serve

Q15. What is the difference between constructor and ngOnInit?

Ans: TypeScript classes has a default method called constructor which is normally used for the initialization purpose. Whereas ngOnInit method is specific to Angular, especially used to define Angular bindings. Even though constructor getting called first, it is preferred to move all of your Angular bindings to ngOnInit method. In order to use ngOnInit, you need to implement OnInit interface as below.

export cexport class App implements OnInit{
  constructor(){
     //called first time before the ngOnInit()
  }
ngOnInit(){
//called after constructor and called  after the first ngOnChanges()
  }
}

Q16. What is a service?

Ans:

A service is used when a common functionality needs to be provided to various modules. Services allow for greater separation of concerns for your application and better modularity by allowing you to extract common functionality out of components.

Let’s create a weatherService which can be used across components.

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

// The Injectable decorator is required for dependency injection to work
@Injectable({
// providedIn option registers the service with a specific NgModule
providedIn: 'root',  // This declares the service with the root app (AppModule)
})
export class WeatherService{
  constructor(private http: HttpClient ){
  }

  fetchAll(){
    return this.http.get('http://weatherapi.com/all');
  }
}

Q17. What is dependency injection in Angular?

Ans: Dependency injection (DI), is an important application design pattern in which a class asks for dependencies from external sources rather than creating them itself. Angular comes with its own dependency injection framework for resolving dependencies( services or objects that a class needs to perform its function).So you can have your services depend on other services throughout your application.

Q19. What is the purpose of async pipe?

Ans:

The AsyncPipe subscribes to an observable or promise and returns the latest value it has emitted. When a new value is emitted, the pipe marks the component to be checked for changes.

Let’s take a time observable which continuously updates the view for every 2 seconds with the current time.

@Component({
  selector: 'async-observable-pipe',
  template: `<div><code>observable|async</code>:
       Time: {{ time | async }}</div>`
})
export class AsyncObservablePipeComponent {
  time = new Observable(observer =>
    setInterval(() => observer.next(new Date().toString()), 2000)
  );
}

Q20. What is the option to choose between inline and external template file?

Ans: By default, the Angular CLI generates components with a template file. But you can override that with the below command.

ng generate component hero -it

Q21. What is the purpose of *ngFor directive?

Ans: We use Angular ngFor directive in the template to display each item in the list. For example, here we iterate over list of posts.

<li *ngFor="let post of posts">
  {{ post}}
</li>

Q22. What is the purpose of ngIf directive?

Ans: Sometimes an app needs to display a view or a portion of a view only under specific circumstances. The Angular ngIf directive inserts or removes an element based on a truthy/falsy condition.

<p *ngIf="post.active" > Am I visible</p>

Q23. What happens if you use script tag inside template?

Ans:

Angular recognizes the value as unsafe and automatically sanitizes it, which removes the <script> tag but keeps safe content such as the text content of the <script> tag. This way it eliminates the risk of script injection attacks. If you still use it then it will be ignored and a warning appears in the browser console.

export class InnerHtmlBindingComponentExample {
  // For example, a user/attacker-controlled value from a URL.
  htmlSnippet = 'Template <script>alert("risk")</script> <b>Syntax</b>';
}

Q24. What is interpolation?

Ans: Interpolation is a special syntax that Angular converts into property binding. It’s a convenient alternative to property binding. It is represented by double curly braces({{}}). The text between the braces is often the name of a component property. Angular replaces that name with the string value of the corresponding component property. Example

<h3>
  {{title}}
  <img src="{{url}}" style="height:30px">
</h3>

Q25. What are template expressions?

Ans: A template expression produces a value similar to any Javascript expression. Angular executes the expression and assigns it to a property of a binding target; the target might be an HTML element, a component, or a directive. In the property binding, a template expression appears in quotes to the right of the = symbol as in [property]=”expression”. In interpolation syntax, the template expression is surrounded by double curly braces. For example, in the below interpolation, the template expression is {{username}}

<h3>{{username}}, welcome to Angular</h3>
The below javascript expressions are prohibited in template expression
> assignments (=, +=, -=, ...)
> new
> chaining expressions with ; or ,
> increment and decrement operators (++ and --)

Q26. What are template statements?

Ans:

A template statement responds to an event raised by a binding target such as an element, component, or directive. The template statements appear in quotes to the right of the = symbol like (event)=”statement”.

Let’s take an example of button click event’s statement

<button (click)="editPost()">Edit Post</button>

In the above expression, editPost is a template statement. The below JavaScript syntax expressions are not allowed.
> new
> increment and decrement operators, ++ and --
> operator assignment, such as += and -=
> the bitwise operators | and &
> the template expression operators

Q27. How do you categorize data binding types?

Ans:

Q28. What are pipes?

Ans: Pipe in the angular used to manipulate the data. Lets say a example. adding a currency symbol before printing the price in the table. or angular provided pipe like date etc.

import { Component } from '@angular/core';

@Component({
  selector: 'app-birthday',
  template: `<p>Birthday is {{ birthday | date }}</p>`
})
export class BirthComponent {
  birthday = new Date(2010, 10, 12); 
}

Q29. What is a parameterized pipe?

Ans: In Angular, we can pass any number of parameters to the pipe using a colon (:) and when we do so, it is called Angular Parameterized Pipes. The syntax to use Parameterized Pipes in Angular Application is given below.

import { Component } from '@angular/core';
    @Component({
      selector: 'date-format',
      template: `<p>Today is {{ todayDate| date:'dd/MM/yyyy'}}</p>` 
    })
    export class TodayComponent {
      todayDate= new Date(1983, 6, 10);
    }

Q30.How do you chain pipes?

Ans: You can chain pipes together in potentially useful combinations as per the needs. Let’s take a birthday property which uses date pipe(along with parameter) and uppercase pipes as below

import { Component } from '@angular/core';
    @Component({
      selector: 'date-format',
      template: `<p>Today is {{ todayDate | date:'dd/MM/yyyy' | uppercase }}</p>` 
    })
    export class TodayComponent {
      todayDate= new Date(1983, 6, 10);
    }

Q31. What is a custom pipe?

Ans: Apart from built-inn pipes, you can write your own custom pipe with the below key characteristics, A pipe is a class decorated with pipe metadata @Pipe decorator, which you import from the core Angular library Ex. @Pipe({name: ‘myCustomPipe’})

The pipe class implements the PipeTransform interface’s transform method that accepts an input value followed by optional parameters and returns the transformed value. The structure of pipeTransform would be as below.

interface PipeTransform {
transform(value: any, …args: any[]): any
}

The @Pipe decorator allows you to define the pipe name that you’ll use within template expressions. It must be a valid JavaScript identifier.
template: {{someInputValue | myCustomPipe: someOtherValue}}

Q32. Give an example of custom pipe?

Ans:

  import { Pipe, PipeTransform } from '@angular/core';

  @Pipe({name: 'fileSize'})
  export class fileSize implements PipeTransform {
    transform(size: number, extension: string = 'MB'): string {
      return (size / (1024 * 1024)).toFixed(2) + extension;
    }
  }

Now you can use the above pipe in template expression as below.

 template: `
      <h2>Find the size of a file</h2>
      <p>Size: {{288966 | fileSize: 'GB'}}</p>
    `

Q33. What is the difference between pure and impure pipe?

Ans: A pure pipe is only called when Angular detects a change in the value or the parameters passed to a pipe. For example, any changes to a primitive input value (String, Number, Boolean, Symbol) or a changed object reference (Date, Array, Function, Object). An impure pipe is called for every change detection cycle no matter whether the value or parameters changes. i.e, An impure pipe is called often, as often as every keystroke or mouse-move.

Q34. What is a bootstrapping module?

Ans: Every application has at least one Angular module, the root module that you bootstrap to launch the application is called as bootstrapping module. It is commonly known as AppModule. The default structure of AppModule generated by AngularCLI would be as follows.

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpClientModule } from '@angular/common/http';

import { AppComponent } from './app.component';

/* the AppModule class with the @NgModule decorator */
@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpClientModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Q35. What are observables?

Ans: Observables are declarative which provide support for passing messages between publishers and subscribers in your application. They are mainly used for event handling, asynchronous programming, and handling multiple values. In this case, you define a function for publishing values, but it is not executed until a consumer subscribes to it. The subscribed consumer then receives notifications until the function completes, or until they unsubscribe.

Q36. What is HttpClient and its benefits?

Ans: Most of the Front-end applications communicate with backend services over HTTP protocol using either XMLHttpRequest interface or the fetch() API. Angular provides a simplified client HTTP API known as HttpClient which is based on top of XMLHttpRequest interface. This client is avaialble from @angular/common/http package. You can import in your root module as below.

import { HttpClientModule } from '@angular/common/http';

The major advantages of HttpClient can be listed as below,

  1. Contains testability features
  2. Provides typed request and response objects
  3. Intercept request and response
  4. Supports Observalbe APIs
  5. Supports streamlined error handling

Q37. Explain on how to use HttpClient with an example?

Ans: Below are the steps need to be followed for the usage of HttpClient.

  • Import HttpClient into root module.
import { HttpClientModule } from '@angular/common/http';
@NgModule({
  imports: [
    BrowserModule,
    // import HttpClientModule after BrowserModule.
    HttpClientModule,
  ],
  ......
  })
 export class AppModule {}
  • Inject the HttpClient into the application: Let’s create a postProfileService(postprofile.service.ts) as an example. It also defines get method of HttpClient
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

const postprofile: string = 'assets/json/post.json';

@Injectable()
export class postProfileService {
  constructor(private http: HttpClient) { }

  getPost() {
    return this.http.get(this.postProfileUrl);
  }
}
fetchPostProfile() {
  this.postProfileService .getPost()
    .subscribe((data: User) => this.user = {
        id: data['userId'],
        name: data['firstName'],
        city:  data['city']
    });
}

Since the above service method returns an Observable which needs to be subscribed in the component.

Q38. How can you read full response?

Ans:

getPost(): Observable<HttpResponse<Post>> {
  return this.http.get<Post>(
    this.userUrl, { observe: 'response' });
}

Q39. How do you perform Error handling?

Ans: If the request fails on the server or failed to reach the server due to network issues then HttpClient will return an error object instead of a successful reponse. In this case, you need to handle in the component by passing error object as a second callback to subscribe() method.

fetchUser() {
  this.userService.getProfile()
    .subscribe(
      (data: User) => this.userProfile = { ...data }, // success path
      error => this.error = error // error path
    );
}

Similar Posts