Angular interview questions
12 questions with answers. 759 open jobs in India ask for Angular.
What is the difference between Promises and Observables?
Promise
A
Promisehandles a single event when an async operation completes or fails.Note: There are
Promiselibraries out there that support cancellation, but ES6Promisedoesn't so far.Observable
An
Observableis like aStream(in many languages) and allows you to pass zero or more events where the callback is called for each event.Often
Observableis preferred overPromisebecause it provides the features ofPromiseand more. WithObservableit doesn't matter if you want to handle 0, 1, or multiple events. You can utilize the same API in each case.Observablealso has the advantage overPromiseto be cancellable. If the result of an HTTP request to a server or some other expensive async operation isn't needed anymore, theSubscriptionof anObservableallows you to cancel the subscription, while aPromisewill eventually call the success or failed callback even when you don't need the notification or the result it provides anymore.While a
Promisestarts immediately, anObservableonly starts if you subscribe to it. This is why Observables are called lazy.Observable provides operators like
map,forEach,reduce, ... similar to an arrayThere are also powerful operators like
retry(), orreplay(), ... that are often quite handy. A list of operators shipped with rxjsLazy 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)
Difference between Constructor and ngOnInit
The
Constructoris 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 callingnew MyClass()it tries to find providers that match the types of the constructor parameters, resolves them and passes them to the constructor likenew MyClass(someArg);ngOnInitis a life cycle hook called by Angular to indicate that Angular is done creating the component.We have to import
OnInitlike this in order to use it (actually implementingOnInitis 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
ngOnInitfor 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)
What is the difference between BehaviorSubject and Observable?
BehaviorSubjectis a variant ofSubject, a type ofObservableto 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
SubjectandBehaviorSubject; 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
BehaviorSubjectfor 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)
- It needs an initial value as it must always return a value upon subscription, even if it has not received the method
What is the equivalent of ngShow and ngHide in Angular 2+?
The
hiddenproperty can be used for that[hidden]="!myVar"See also
issues
hiddenhas some issues though because it can conflict with CSS for thedisplayproperty.See how
somein 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 valuefalseor 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 thisfalseis assigned asfalseinstead of"false".*ngIfvs[hidden]*ngIfeffectively removes its content from the DOM while[hidden]modifies thedisplayproperty 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)
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.
- For example, if a package has the scope
- The package name only has to be unique to the scope it is published in, not the entire registry.
- For example, the package name
httpis already taken in the main repository, but Angular is able to have@angular/httpas well.
- For example, the package name
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)
- It allows organizations to make it clear which packages are 'official' and which ones are not.
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
*ngIfof an element, and I was trying to change that flag inside of thengOnInit()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)
What is the difference between declarations, providers, and import in NgModule?
Angular Concepts
importsmakes the exported declarations of other modules available in the current moduledeclarationsare 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.providersare 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
providersare lazy loaded modules that get their own child injector.providersof 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
exportsmakes the components, directives, and pipes available in modules that add this module toimports.exportscan also be used to re-export modules such as CommonModule and FormsModule, which is often done in shared modules.entryComponentsregisters components for offline compilation so that they can be used withViewContainerRef.createComponent(). Components used in router configurations are added implicitly.
TypeScript (ES2015) imports
import ... from 'foo/bar'(which may resolve to anindex.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()importsand TypeScriptimportare 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)
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:
BehaviorSubjectshould be created with an initial value: newRx.BehaviorSubject(1)- Consider
ReplaySubjectif you want the subject to get previously published values.
From Stack Overflow: asked by Mike Jerred, answered by ZahiC (CC BY-SA 4.0)
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)
Angular HTML binding
The correct syntax is the following:
<div [innerHTML]="theHtmlString"></div>From Stack Overflow: asked by Aviad P., answered by prolink007 (CC BY-SA 4.0)
Angular/RxJS When should I unsubscribe from `Subscription`
TL;DR
For this question there are two kinds of Observables - finite value and infinite value.
httpObservables produce finite (1) values and something like a DOM event listener Observable produces infinite values.If you manually call
subscribe(not using async pipe), thenunsubscribefrom 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)
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
thenalone:<div *ngIf="isValid;then content"></div> <ng-template #content>content here...</ng-template>Demo:
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
ngIfdirective but with support forelse 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
@ifand@else ifsyntax makes it easier to express conditional logic. - No Need for
CommonModule: UnlikengIf, the control flow syntax doesn’t require importing theCommonModule.
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)
- Simplified Conditional Logic: The
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.
- Stack Overflowby its contributors, named on each answerCC BY-SA12 questions