All topics

Angular interview questions

12 questions with answers. 759 open jobs in India ask for Angular.

  1. What is the difference between Promises and Observables?

    Promise

    A Promise handles a single event when an async operation completes or fails.

    Note: There are Promise libraries out there that support cancellation, but ES6 Promise doesn't so far.

    Observable

    An Observable is like a Stream (in many languages) and allows you to pass zero or more events where the callback is called for each event.

    Often Observable is preferred over Promise because it provides the features of Promise and more. With Observable it doesn't matter if you want to handle 0, 1, or multiple events. You can utilize the same API in each case.

    Observable also has the advantage over Promise to be cancellable. If the result of an HTTP request to a server or some other expensive async operation isn't needed anymore, the Subscription of an Observable allows you to cancel the subscription, while a Promise will eventually call the success or failed callback even when you don't need the notification or the result it provides anymore.

    While a Promise starts immediately, an Observable only starts if you subscribe to it. This is why Observables are called lazy.

    Observable provides operators like map, forEach, reduce, ... similar to an array

    There are also powerful operators like retry(), or replay(), ... that are often quite handy. A list of operators shipped with rxjs

    Lazy execution allows you to build up a chain of operators before the observable is executed by subscribing, to do a more declarative kind of programming.

    From Stack Overflow: asked by Rohit, answered by Günter Zöchbauer (CC BY-SA 4.0)

  2. Difference between Constructor and ngOnInit

    The Constructor is a default method of the class that is executed when the class is instantiated and ensures proper initialisation of fields in the class and its subclasses. Angular, or better Dependency Injector (DI), analyses the constructor parameters and when it creates a new instance by calling new MyClass() it tries to find providers that match the types of the constructor parameters, resolves them and passes them to the constructor like

    new MyClass(someArg);
    

    ngOnInit is a life cycle hook called by Angular to indicate that Angular is done creating the component.

    We have to import OnInit like this in order to use it (actually implementing OnInit is not mandatory but considered good practice):

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

    then to make use of the method OnInit, we have to implement the class like this:

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

    Implement this interface to execute custom initialization logic after your directive's data-bound properties have been initialized. ngOnInit is called right after the directive's data-bound properties have been checked for the first time, and before any of its children have been checked. It is invoked only once when the directive is instantiated.

    Mostly we use ngOnInit for all the initialization/declaration and avoid stuff to work in the constructor. The constructor should only be used to initialize class members but shouldn't do actual "work".

    So you should use constructor() to setup Dependency Injection and not much else. ngOnInit() is better place to "start" - it's where/when components' bindings are resolved.

    For more information refer here:

    Important to note that @Input values are not accessible in the constructor (Thanks to @tim for suggestion in comments)

    From Stack Overflow: asked by Haseena P A, answered by Pardeep Jain (CC BY-SA 4.0)

  3. What is the difference between BehaviorSubject and Observable?

    BehaviorSubject is a variant of Subject, a type of Observable to which one can "subscribe" like any other Observable.

    Features of BehaviorSubject

    • It needs an initial value as it must always return a value upon subscription, even if it has not received the method next()
    • Upon subscription, it returns the last value of the Subject. A regular Observable is only triggered when it receives the method onNext()
    • At any point, one can retrieve the last value of the Subject in a non-Observable using the method getValue()

    Features of Subject

    • Subject is an "observer" in addition to being an Observable; therefore, one can also send values to a Subject while also subscribing to it
    • One can get a value from BehaviorSubject using the method asObservable()

    Example 1 using BehaviorSubject

    // BehaviorSubject.
    // 'A' is an initial value. If there is a Subscription 
    // after it, it would immediately get the value 'A'.
    beSubject = new BehaviorSubject('a'); 
    beSubject.next('b');
    beSubject.subscribe(value => {
      console.log('Subscription received the value ', value);
      // Subscription received B. It would not happen
      // for an Observable or Subject by default.
    });
    beSubject.next('c');
    // Subscription received C.
    beSubject.next('d');
    // Subscription received D.
    

    Example 2 using Subject

    // Subject.
    subject = new Subject(); 
    subject.next('b');
    subject.subscribe(value => {
      console.log('Subscription received the value ', value);
      // Subscription won't receive anything at this point.
    });
    subject.next('c');
    // Subscription received C.
    subject.next('d');
    // Subscription received D.
    

    An Observable can be created from both Subject and BehaviorSubject; for example, subjectName.asObservable().

    The only difference is that one cannot send values to an Observable using the method next().

    In Angular, it is recommended to use BehaviorSubject for transferring data as a Service is often initialised before a component.

    BehaviorSubject ensures that the component consuming the Service receives the last updated data, even if there are no new updates, due to the subscription of the component to the Service.

    From Stack Overflow: asked by Kevin Mark, answered by Shantanu Bhadoria (CC BY-SA 4.0)

  4. What is the equivalent of ngShow and ngHide in Angular 2+?

    The hidden property can be used for that

    [hidden]="!myVar"
    

    See also

    issues

    hidden has some issues though because it can conflict with CSS for the display property.

    See how some in Plunker example doesn't get hidden because it has a style

    :host {display: block;}
    

    set. (This might behave differently in other browsers - I tested with Chrome 50)

    workaround

    You can fix it by adding

    [hidden] { display: none !important;}
    

    To a global style in index.html.

    another pitfall

    hidden="false"
    hidden="{{false}}"
    hidden="{{isHidden}}" // isHidden = false;
    

    are the same as

    hidden="true"
    

    and will not show the element.

    hidden="false" will assign the string "false" which is considered truthy.
    Only the value false or removing the attribute will actually make the element visible.

    Using {{}} also converts the expression to a string and won't work as expected.

    Only binding with [] will work as expected because this false is assigned as false instead of "false".

    *ngIf vs [hidden]

    *ngIf effectively removes its content from the DOM while [hidden] modifies the display property and only instructs the browser to not show the content but the DOM still contains it.

    From Stack Overflow: asked by Mihai Răducanu, answered by Günter Zöchbauer (CC BY-SA 4.0)

  5. What is the meaning of the "at" (@) prefix on npm packages?

    This is a new feature of NPM called 'scoped packages', which effectively allow NPM packages to be namespaced. Every user and organization on NPM has their own scope, and they are the only people who can add packages to it.

    This is useful for several reasons:

    • It allows organizations to make it clear which packages are 'official' and which ones are not.
      • For example, if a package has the scope @angular, you know it was published by the Angular core team.
    • The package name only has to be unique to the scope it is published in, not the entire registry.
      • For example, the package name http is already taken in the main repository, but Angular is able to have @angular/http as well.

    The reason that scoped packages don't show up in public search is because a lot of them are private packages created by organizations using NPM's paid services, and they're not comfortable opening the search up until they can be totally certain they're not going to make anything public that shouldn't be public - from a legal perspective, this is pretty understandable.

    For more information, see the NPM docs and the Angular docs.

    EDIT: It appears that public scoped packages now show up properly in search!

    From Stack Overflow: asked by jbandi, answered by Joe Clay (CC BY-SA 4.0)

  6. ExpressionChangedAfterItHasBeenCheckedError Explained

    A lot of understanding came once I understood the Angular Lifecycle Hooks and their relationship with change detection.

    I was trying to get Angular to update a global flag bound to the *ngIf of an element, and I was trying to change that flag inside of the ngOnInit() life cycle hook of another component.

    According to the documentation, this method is called after Angular has already detected changes:

    Called once, after the first ngOnChanges().

    So updating the flag inside of ngOnChanges() won't initiate change detection. Then, once change detection has naturally triggered again, the flag's value has changed and the error is thrown.

    In my case, I changed this:

    constructor(private globalEventsService: GlobalEventsService) {
    }
    ngOnInit() {
        this.globalEventsService.showCheckoutHeader = true;
    }
    

    To this:

    constructor(private globalEventsService: GlobalEventsService) {
        this.globalEventsService.showCheckoutHeader = true;
    }
    ngOnInit() {
    }
    

    and it fixed the problem :)

    From Stack Overflow: asked by Kevin LeStarge, answered by Kevin LeStarge (CC BY-SA 3.0)

  7. What is the difference between declarations, providers, and import in NgModule?

    Angular Concepts

    • imports makes the exported declarations of other modules available in the current module
    • declarations are to make directives (including components and pipes) from the current module available to other directives in the current module. Selectors of directives, components or pipes are only matched against the HTML if they are declared or imported.
    • providers are to make services and values known to DI (dependency injection). They are added to the root scope and they are injected to other services or directives that have them as dependency.

    A special case for providers are lazy loaded modules that get their own child injector. providers of a lazy loaded module are only provided to this lazy loaded module by default (not the whole application as it is with other modules).

    For more details about modules see also https://angular.io/docs/ts/latest/guide/ngmodule.html

    • exports makes the components, directives, and pipes available in modules that add this module to imports. exports can also be used to re-export modules such as CommonModule and FormsModule, which is often done in shared modules.

    • entryComponents registers components for offline compilation so that they can be used with ViewContainerRef.createComponent(). Components used in router configurations are added implicitly.

    TypeScript (ES2015) imports

    import ... from 'foo/bar' (which may resolve to an index.ts) are for TypeScript imports. You need these whenever you use an identifier in a typescript file that is declared in another typescript file.

    Angular's @NgModule() imports and TypeScript import are entirely different concepts.

    See also jDriven - TypeScript and ES6 import syntax

    Most of them are actually plain ECMAScript 2015 (ES6) module syntax that TypeScript uses as well.

    From Stack Overflow: asked by Ramesh Papaganti, answered by Günter Zöchbauer (CC BY-SA 4.0)

  8. What is the difference between Subject and BehaviorSubject?

    A BehaviorSubject holds one value. When it is subscribed it emits the value immediately. A Subject doesn't hold a value.

    Subject example (with RxJS 5 API):

    const subject = new Rx.Subject();
    subject.next(1);
    subject.subscribe(x => console.log(x));
    

    Console output will be empty

    BehaviorSubject example:

    const subject = new Rx.BehaviorSubject(0);
    subject.next(1);
    subject.subscribe(x => console.log(x));
    

    Console output: 1

    In addition:

    • BehaviorSubject should be created with an initial value: new Rx.BehaviorSubject(1)
    • Consider ReplaySubject if you want the subject to get previously published values.

    From Stack Overflow: asked by Mike Jerred, answered by ZahiC (CC BY-SA 4.0)

  9. Angular: conditional class with *ngClass

    Angular version 2+ provides several ways to add classes conditionally:

    Type one

    [class.my_class] = "step === 'step1'"
    

    Type two

    [ngClass]="{'my_class': step === 'step1'}"
    

    and multiple options:

    [ngClass]="{'my_class': step === 'step1', 'my_class2' : step === 'step2' }"
    

    Type three

    [ngClass]="{1 : 'my_class1', 2 : 'my_class2', 3 : 'my_class4'}[step]"
    

    Type four

    [ngClass]="step == 'step1' ? 'my_class1' : 'my_class2'"
    

    You can find these examples on the the documentation page.

    From Stack Overflow: asked by daniel, answered by MostafaMashayekhi (CC BY-SA 4.0)

  10. Angular HTML binding

    The correct syntax is the following:

    <div [innerHTML]="theHtmlString"></div>
    

    Documentation Reference

    From Stack Overflow: asked by Aviad P., answered by prolink007 (CC BY-SA 4.0)

  11. Angular/RxJS When should I unsubscribe from `Subscription`

    TL;DR

    For this question there are two kinds of Observables - finite value and infinite value.

    http Observables produce finite (1) values and something like a DOM event listener Observable produces infinite values.

    If you manually call subscribe (not using async pipe), then unsubscribe from infinite Observables.

    Don't worry about finite ones, RxJs will take care of them.

    Sources:

    Read the rest at the sourceFrom Stack Overflow: asked by Sergey Tihon, answered by seangwright (CC BY-SA 4.0)

  12. How can I use "*ngIf else"?

    Angular 4 and 5:

    Using else:

    <div *ngIf="isValid;else other_content">
        content here ...
    </div>
    <ng-template #other_content>other content here...</ng-template>
    

    You can also use then else:

    <div *ngIf="isValid;then content else other_content">here is ignored</div>
    <ng-template #content>content here...</ng-template>
    <ng-template #other_content>other content here...</ng-template>
    

    Or then alone:

    <div *ngIf="isValid;then content"></div>
    <ng-template #content>content here...</ng-template>
    

    Demo:

    Plunker

    Details:

    <ng-template>: is Angular’s own implementation of the <template> tag which is according to MDN:

    The HTML <template> element is a mechanism for holding client-side content that is not to be rendered when a page is loaded but may subsequently be instantiated during runtime using JavaScript.

    Update (Angular 17 and higher)

    Angular now supports control flow syntax (introduced in Angular 17), which allows you to write cleaner and more expressive conditional logic directly in templates. This new syntax enables functionality similar to the ngIf directive but with support for else if.

    Here’s how you can use it:

    @if (a > b) {
      {{a}} is greater than {{b}}
    } @else if (b > a) {
      {{a}} is less than {{b}}
    } @else {
      {{a}} is equal to {{b}}
    }
    

    Benefits:

    • Simplified Conditional Logic: The @if and @else if syntax makes it easier to express conditional logic.
    • No Need for CommonModule: Unlike ngIf, the control flow syntax doesn’t require importing the CommonModule.

    This feature is particularly helpful for scenarios where you have multiple conditions to check in your templates, improving both readability and maintainability.

    From Stack Overflow: asked by El houcine bougarfaoui, answered by El houcine bougarfaoui (CC BY-SA 4.0)

Related topics

Where these questions come from

Open-source collections on GitHub, official documentation, a government careers service and the Stack Exchange sites, each used under its own licence. The answers are the authors' own words: we only tidy the layout, leave out pictures, and cut a long answer with a link to the rest. Stack Exchange answers stay under CC BY-SA and name who asked and who answered.