Top 10 Angular Interview Questions and Answers

Most frequently asked Angular interview questions and answers for experienced and freshers. These top 10 angular interview questions are for Angular 2, Angular 4, Angular 6, Angular 7, Angular 8, angular 10, angular 11, and angular 12. We have covered the top 10 most important basic Angular interview questions for experienced and freshers.

Following are frequently asked basic Angular interview questions. These basics interview questions will help you to clear your full stack developer, frontend developer interview.

Why should ngOnInit be used, if we already have a constructor?

A constructor is the default method of the class which is called whenever an object is created. It ensures the initialization of the class members in the class and its child classes. In Angular, ngOnInit() is one of the component’s life hooks which runs first after the constructor(default method) when the component is initialized.

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  constructor(private userService: UserService) {
    console.log("Called first time before the ngOnInit()");
  }
  ngOnInit() {
    this.userService.getUser();
    console.log("Called after the constructor ");
  }
} 

How will you share the data between components?

Four most common methods for sharing data between Angular components.

  1. Sharing Data via Input
  2. Sharing Data via ViewChild
  3. Sharing Data via Output() and EventEmitter
  4. Sharing Data with a Service

for more details please check out the article “Sharing data between components in angular 11 – @input, @Output, @ViewChild, and Service

What is Data Binding in Angular 8?

One-way data binding: it is unidirectional and can be achieved through different techniques.  

  • Interpolation Binding
  • Property Binding
  • Attribute Binding
  • Class Binding
  • Style Binding

Two-way data binding: it is nothing but both property binding & event binding applied together. We can use the ngModel directive in two-way data binding.

for more details please check out the article Data Binding In Angular 11: one-way and two-way data binding

What are the lifecycle hooks in angular?

Each Angular component goes through lifecycle hooks. When it is initialized and executed depending on the conditions of the current cycle.

These are the hooks for components, in call order.

  • ngOnChanges()
  • ngOnInit()
  • ngDoCheck()
  • ngAfterContentInit()
  • ngAfterContentChecked()
  • ngAfterViewInit()
  • ngAfterViewChecked()
  • ngOnDestroy()

for more details please check out  here

What are the observables in Angular?

Observable is a sequence of data that is emitted asynchronously over a period of time. whenever there is a change in the data it is automatically updated and tracked by our observable. Use of observables as an interface to handle a variety of common asynchronous operations they are frequently used in angular for event handling, asynchronous programming, and handling multiple values.

in other words, Observables follow the Observer pattern, where a single piece of state is watched by one or more Observers which can react as it changes over time.


import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';

@Injectable({
    providedIn: 'root'
})
export class UserService {

    users: User[] = [{
        id: 1,
        name: 'User 1',
        enrollmentnumber: 1002,
        department: 'Test Engineering department',
        company: 'GTU'
    },
    {
        id: 2,
        name: 'User 2',
        enrollmentnumber: 1001,
        department: 'Test Engineering department',
        company: 'GTU'
    }];

    constructor() { }

    public getUsers(): Observable<Array<User>> {
        return new Observable((observer: User) => {
            observer.next(this.users);
        });
    }
} 
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {

    users: any[] = [];

    constructor(private userService: UserService) {}

    ngOnInit() {
        this.userService.getUsers().subscribe((res: User[]) => {
            this.users = res;
        });
    }
} 

What are the differences between promises and observables in Angular 8?

Promises and Observables are two through which we can perform the asynchronous operations in Angular. here are the differences between them:

  • Promises are one way of dealing with asynchronous functions. they are not cancellable they’re either resolved or rejected and Observable are re-triable by nature such as retry and retryWhen.
  • Observables can provide multiple values over time but Promises provide only one value.
  • Promise Does not provide any operators and Observable Provides the map, forEach, filter, reduce, retry, and retryWhen operators

What is singleton searcive and how to make a service a singleton in Angular?

Singleton is a Creational design pattern for which only one instance exists in an app. There are two ways to make a service a singleton in Angular

  1. Set the providedIn property of the @Injectable() to “root“.
  2. Include the service in the AppModule.

Following is an example of how the set the providedIn property of the @Injectable() to “root“.

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

@Injectable({
  providedIn: 'root',
})
export class EmployeeService {
} 

Following is an example of how the set the service in the AppModule.

@NgModule({
  
  providers: [EmployeeService],
  
}) 

What is the HTTP interceptor and how to add token in request?

HttpInterceptors provide a mechanism to intercept the outgoing request and incoming responses of network-related resources. They are very similar to the concept of middleware.

import { Injectable } from '@angular/core';
import {HttpRequest, HttpHandler, HttpEvent, HttpInterceptor
} from '@angular/common/http';
import { AuthService } from '@auth/auth.service';
import { Observable } from 'rxjs/Observable';
@Injectable()
export class AuthTokenInterceptor implements HttpInterceptor {
    constructor(public auth: AuthService) { }
    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

        request = request.clone({
            setHeaders: {
                Authorization: `Bearer ${this.auth.getToken()}`
            }
        });
        return next.handle(request);
    }
} 

Using the intercept() method we need to clone the original request, modify it, and then call next.handle() to pass the modified request. AuthTokenInterceptor should be provided using HTTP_INTERCEPTORS injection token in AppModule.

@NgModule({
  // ...
  providers: [ 
    { provide: HTTP_INTERCEPTORS, useClass: TokenInterceptor, multi: true },
  ],
})
export class AppModule { } 
  • Post category:Angular
  • Reading time:6 mins read