Angular Inteview Questions

Angular Interview Qestions

1. What is Angular?

2. What is Angular Framework?

3. What is the difference between AngularJS and Angular?

4. What is TypeScript?

5. What's new in Angular 2?

6. What’s new an angular 4?

7. What’s new an angular 5?

8. What’s new an angular 6?

9. What’s new in angular 7?

9. What’s new in angular 8?

10. What’s new in angular 9?

11. What are the key components of Angular?

12. What is module?

13. What is NgModule?

14. Why use multiple NgModules?

15. How many Types of NgModules?

16. What are the properties of NgModule?

17. What are directives?

18. How many types for directives?

19. What are components?

20. What are the differences between Component and Directive?

21. What is a template?

22. What are lifecycle hooks available?

23. What is a data binding?

24. What is metadata?

25. What is angular CLI?

26. What is the difference between constructor and ngOnInit?

27. What are the @Component configuration options?

28. What is a service?

29. What is @Injectable() services?

30. How to inject service in root level?

31. What is dependency injection in Angular?

32. What is the purpose of async pipe?

34. What is the purpose of ngFor directive?

35. What is the purpose of ngIf directive?

36. What is the purpose of NgSwitch directive?

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

38. What is interpolation?

39. What are template expressions?

40. What are pipes?

41. What is a parameterized pipe?

42. How do you chain pipes?

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

44. How to make pipe or impure pure?

45. How to create custom pipe?

46. What is a bootstrapping module?

47. What is observable?

48. What is RxJS?

49. What is subscribing?

50. What is an observer?

51. What is an Operator?

52. What is catchError RxJS operator?

53. What is multicasting?

54. What are RxJS subjects?

55. What are the Subject types?

56. What is Behavior subject?

57. What is Replay Subject?

58. What is Async Subject?

59. What are angular elements?

60. What is the browser support of Angular Elements?

61. What are custom elements?

62. Explain how custom elements works internally?

63. How to transfer components to custom elements?

64. What is Angular Router?

65. What is the purpose of base href tag?

66. What are the router imports?

67. What is router outlet?

68. What are router links?

69. What is active router link?

70. What is router state?

71. What is activated route?

72. What is the purpose of Wildcard route?

73. How do you define routes?

74. Do you need a Routing Module?

75. What are the advantages of Routing module?

76. What is ParamMap in angular?

77. What is the difference between ActivatedRoute and RouterState/ ActivatedRouteSnapshot?

78. Why route parameters are observables?

79. How can you register routes?

80. How to configure Route with parameters?

81. How to pass route parameters in RouterLink?

82. How to navigate to some route from ts file?

83. List out the router events?

84. What are observable creation functions?

85. What are different types of compilation in Angular?

86. What is JIT?

87. What is AOT?

88. Why do we need compilation process?

89. What are the advantages with AOT?

90. Can I use arrow functions in AOT?

91. What is type narrowing?

92. What are differences between a Promise and an Observable ?

93. What is dynamic routing?

94. What are differences between Constructors and OnInit?

95. What is redirectTo in angular?

96. What is Empty-path route configurations?

97. What is Matching Strategy route configurations?

98. what is componentless routes in angular?

99. what is lazy loading in angular

100. What are some advantages of lazy loading in angular ?

1. What is Angular?

Angular is a JavaScript framework for building we, mobile and desktop applications in JavaScript, html, and TypeScript. TypeScript is a superset of JavaScript.

2. What is Angular Framework?

Angular is an open-source front-end platform which makes easy to create applications for web, mobile and desktop, have some features like declarative, dependency injection template, routing etc

3. What is the difference between AngularJS and Angular?

Some majors difference are as follows:

Angular JS

Angular

Supports Model-View-Controller(MVM) design. The view processes the information available in the model to generate the output

Uses directives and components. Components are the directives within the template.

Written in JavaScript

Written in TypeScript

Binding of image/property or an event developer need to remember the right  ng directive

Use "()" for event binding and "[]" for property binding

Does not provide mobile friendly

  Mobile Friendly

Uses @routeprovider.when() for routing configuration

uses @RouteConfig{{....}} for  routing configuration

Does not support Dependency Injection

Support Dependency Injection

Less manageable in compare to angular

Better structure, easier to create and maintain large applications

Does not support Ahead of Time compilation (AOT)

Support Ahead of Time compilation (AOT)

No support or new updates are provided anymore.

Active support and frequent new updates are made.

Service, factory, provider, value and constant are used for services

class is the only way to define services

Run on only client-side

Runs on client-side and server-side

4. What is TypeScript?

TypeScript  is an open-source programming language and it is a strongly typed superset of JavaScript.  TypeScript makes JavaScript complete programming languages, adds strongly type declarative structure to JavaScript programming. TypeScript uses JavaScript and follow the C#  programming language syntaxes and complies with native JavaScript.

TypeScript was developed and manage by Microsoft. TypeScript uses a trans compiler or transpiler to translate the typescript code into JavaScript.

5. What's new in Angular 2?

Angular 2 feature as follows:

  • Dependency Injection (DI) : Dependency Injection software design pattern which is use for registering the service and DI will take care of object creation.
  • Directives : -The directive is declared as @Directive annotation.
  • TypeScript : Angular 2 use the typescript programming language to coding.
  • Generic : Its support the typescript generic features.
  • Dynamic Loading : You can load the components and directive on run time.
  • Lambdas and Arrow functions : Lambdas and Arrow functions supporting by typescript so you can these in angular 2 applications.
  • Modules : Angular 2 support modules, its break your project in logical peace of code.

6. What’s new an angular 4?

Angular 4 features as follows:

  • Animation Package
  • Template Changes
  • Router
  • Speed and Performance
  • Angular Universal
  • ngIf and else
  • NgIf and ngFor Improvement
  • Supported as keyword
  • Introduced new titlecase pipe
  • Simplified HTTP request
  • App testing simplified
  • Introduced Meta Tags
  • Added new form validators
  • Dynamic Components with NgComponentOutlet
  • TypeScript 2.1/2.2
  • StrictNullChecks
  • Forms get assigned “novalidate” automatically
  • Source maps also for templates
  • Flat ES-Modules (Flat ESM / FESM)
  • I18n Internationalization Improvement

7. What’s new an angular 5?

Angular 5 changes are as follows:

  • Http Deprecated, HttpClient continue
  • Support for Multiple Export Alias in Angular
  • Internationalized Number, Date, and Currency Pipes
  • Improved Decorator Support
  • Build Optimization
  • Angular Universal Transfer API
  • Faster Compiler
  • Forms Validation are updated via on blur or on submit
  • Animations : two new transition aliases, :increment and :decrement.
  • New Router Lifecycle Events : GuardsCheckStart, ChildActivationStart, ActivationStart, GuardsCheckEnd, ResolveStart, ResolveEnd, ActivationEnd, and ChildActivationEnd
  • Better Support for Service Workers
  • Make AOT by default
  • RxJS 5.5.2
  • CLI v1.5
  • Enhanced Decorator support
  • Zone speed improvements
  • Preserve Whitespace

8. What’s new an angular 6?

Angular 6 new changes as follows:

  • ng update
  • ng add
  • CLI Material Starter Templates
  • Material Sidenav
  • Material Dashboard
  • Material Data Table
  • Registering Providers
  • RxJS V6
  • Ivy Renderer

9. What’s new in angular 7?

  • CLI prompts
  • Angular material & component dev kit (CDK)
  • Drag & drop
  • Virtual scrolling
  • Application performance improvements
  • Bundle Budget
  • Angular Do-Bootstrap
  • Better Error Handling
  • Native Script
  • support Typescript 3.1, Node 10 and RxJS 6.3.

9. What’s new in angular 8?

  • Dynamic imports for lazy routes
  • Differential loading
  • CLI workflow improvements
  • Improved web worker bundling
  • Angular router backwards compatibility
  • Support TypeScript 3.4
  • Dart-sass for Sass files

10. What’s new in angular 9?

  • Smaller bundles and better performance
  • Added undecorated classes migration schematic in the core.
  • Support for TypeScript Diagnostics Format.
  • The formControlName also accepts a number in the form.
  • Internationalization support for Angular Ivy.
  • Selector-less directives as base classes in View Engine in the compiler.
  • Added support for selector-less directive as base classes in Ivy.
  • Ivy compiler is now the default for ngc.
  • Convert all ngtsc diagnostics to ts.Diagnostics.
  • Bazel: support ts_librarytargets as entry-points for ng_package.
  • Core: add dynamic queries schematic.
  • Core: Mark getas deprecated.
  • Ivy: expose ng.getDebugNodehelper and also support ng-add in localize package.
  • Ivy: i18n —add syntax support for $localizemetadata block.
  • Ivy: i18n — reorganize entry-points for better reuse.
  • Language-service: enable logging on TypeScriptHost.
  • Language-service: provide diagnostic for invalid templateUrls.
  • Language-service: provide diagnostics for invalid styleUrls.

11. Write a pictorial diagram of Angular architecture?

11. Write a pictorial diagram of Angular architecture?

As per angular office document, see the below pictorial diagram of angular architecture.

Angular Interview Qestions

11. What are the key components of Angular?
Or
What are the main building blocks of Angular?
Or
What are the core components of angular?

Main building blocks of angular application are as follows:

  • Modules
  • Components
  • Templates
  • Metadata
  • Data binding
  • Directives
  • Services
  • Dependency injection

12. What is module?

Modules are piece of code and its break of break your application into small-small group of tasks.

13. What is NgModule?

An NgModule is group of metadata which describing components, services, directives, pipes, etc. When we add these resources to the NgModule metadata and angular creates a component factory, which is just a typescript class that churns out components.

NgModule: are built with metadata and some of them are as follows :

  • declarations : Declare component to make them privately available in this module.
  • exports : To makes the declared components public so they can be used by other modules.
  • imports : import the other modules features.
  • providers : Register the service to dependency injection.

bootstrap - The component used to launch the app and the AppComponent component by default. All angular applications must have at least one

  

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

14. Why use multiple NgModules?

NgModules provides below benefits.

  • It makes your business logic organized. You can create feature wise module so it easy to manage/ organize
  • Give you the option to make your module lazy loading via the router.

15. How many Types of NgModules?

There are five types of module in angular and these are as follows:

  • Domain modules: Dedicated to a particular application domain and imported by AppModule for example customer module, order module etc.
  • Routed modules : use for router navigation routes and all lazy-loaded modules are routed feature modules. Routed feature modules do not export anything because its components never appear in the template of an external component
  • Routing modules : Use for routing configuration
  • Service modules: Use for services/providers.
  • Widget modules : module make the components, directives, and pipes available to external modules.

16. What are the properties of NgModule?

NgModule properties are as follows:

providers : The providers is an array that contains the list of injectable services that are available for this NgModule. Providers have a scope, and if they are listed in a lazy-loaded NgModule, they are not available outside of that NgModule.

declarations:   The array of components, directives, and pipes (declarables) that belong to this module only.

imports :  Array of NgModules whose exported declarables are available to templates or components in this module .

exports: The array of components, directives, and pipes declared in this NgModule. It can be used in the template of any component that is part of an NgModule that imports this NgModule.

 

entryComponents: The array of components to compile when this NgModule is defined, so that they can be dynamically loaded into the view.

bootstrap: The array of components that are bootstrapped when this module is bootstrapped. The components listed in  bootstrap  are automatically added to entryComponents.

schemas: The array of schemas that declare elements to be allowed in the NgModule. Properties and elements that are neither Angular components nor directives must be declared in a schema.

id: A name that uniquely identifies this NgModule in getModuleFactory. the NgModule is not registered with getModuleFactory,  if it left undefined.

jit : If true then this module will be skipped by the AOT compiler and so will always be compiled using JIT.

17. What are directives?

Directives add behaviour to an existing DOM element or an existing component instance.
Directive changes the behaviour or appearance of a DOM element or an existing component .

  

        import { Directive, ElementRef } from '@angular/core';

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

Change the html element behaviour with red background as below

  

<p appHighlight>Highlight me!</p>
    

18. How many types for directives?

There are three types of directive in angular and these are as follows:

 

  • Components : It is a directive with a template.
  • Structural directives : These directives change of DOM layout element by adding and removing DOM elements. For example, NgFor,NgIf etc.
  • Attribute directives : These directives change the behaviour or appearance of an element, component, or another directive. For example, ngStyle, ngClass etc.

19. What are components?

Components are the building block of an UI in an Angular application. An Angular apps are tree of Angular components. Angular components are a one of the directives. Unlike other directives, only one component can be instantiated per an element in a template.

  

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

        @Component({
        selector: 'my-app',
        templateUrl: './app.component.html',
        styleUrls: [ './app.component.css' ]
        })
        export class AppComponent  {
        name = 'Angular';
        }

    

20. What are the differences between Component and Directive?

Components

Directive

To register component use @Component meta-data annotation.

To register directives use @Directive meta-data annotation.

Components are mainly used to create UI widgets.

Directive is used to change the  behaviour of an existing DOM element

It is used to break up the application into smaller components.

It is used to design re-usable components.

Only one component can be allowed per DOM element.

Many directives can be used in a per DOM element.

@View decorator or template/ templateurl are mandatory

Does not use View

viewEncapsulation can be define in components because they have views.

Directive do not have views. So, you cannot use viewEncapsulation in directive.

Component is used to define pipes.

You cannot define Pipes in directive.

21. What is a template?

A template is an HTML snippet that tells Angular app how to render the component in angular application. You can store the component template in two places these are as follows.

A) Inline Template : The inline template is stored by placing the HTML code in back ticks`` and linked to the component metadata using the template property of @Component decorator.
  

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

             @Component({
             selector: 'my-app',
             template:`<div>
                 Angular Interview Question
             </div>`,
             styleUrls: [ './app.component.css' ]
             })
             export class AppComponent  {
             name = 'Angular';
             public isActive=true;
             }


         

B) Template File : The template is defined in a separate HTML file and its linked to the component metadata using the @Component decorator templateUrl property.

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

  

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

        @Component({
        selector: 'my-app',
        templateUrl: './app.component.html',
        styleUrls: [ './app.component.css' ]
        })
        export class AppComponent  {
        title = 'Angular Interview Questions ';

        }
    

22. What are lifecycle hooks available?

There are 8 angular page lifecycle, and these are as follows:

 

  • ngOnChanges: This method is called When the value of a data bound property changes.
  • ngOnInit: This is called whenever the initialization of the directive/component after Angular first displays the data-bound properties happens.
  • ngDoCheck: This is for the change detection and to act on changes that Angular cannot or won't detect on its own.
  • ngAfterContentInit: This is called in response after Angular projects external content into the component's view.
  • ngAfterContentChecked: This is called in response after Angular checks the content projected into the component.
  • ngAfterViewInit: This is called in response after Angular initializes the component's views and child views.
  • ngAfterViewChecked: This is called in response after Angular checks the component's views and child views.
  • ngOnDestroy: This is the clean-up phase just before Angular destroys the directive/component.

23. What is a data binding?

Data binding is a core concept of Angular application which allows to define communication between a component and the DOM element, it makes very easy to define interactive applications without worrying about pushing and pulling data.

There are four types of data binding in angular and these are as follows:

A) Interpolation : {{ value }} adds the value of a property from the component

app.component.ts file

  

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

        @Component({
        selector: 'my-app',
        templateUrl: './app.component.html',
        styleUrls: [ './app.component.css' ]
        })
        export class AppComponent  {
        firstName='John';
        lastName='Doe'

        }
    

app.component.html file

  

<h3> Angular Interview Question </h3>

<p> First Name : {{firstName}} </p>
<p> Last Name : {{lastName}} </p>
    

B) Property binding : Value is passed from the component to the specified property, which can be a simple html attribute:

Syntax : [property]=”value”

Example

app.component.ts file

  

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

        @Component({
        selector: 'my-app',
        templateUrl: './app.component.html',
        styleUrls: [ './app.component.css' ]
        })
        export class AppComponent  {
        firstName='John';
        lastName='Doe'
        }

    

app.component.html file

C) Event binding : When a specific DOM event happens like click, change, keyup etc., then call the specified method of the component.

Syntax : (event)=”functionName()”

Example :

app.component.ts file

  

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

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

        onDoneClicked(){
        console.log('On Done Button Clicked')
        }
        }

    

app.component.html file

  

<h3> Angular Interview Question </h3>

<button (click)="onDoneClicked()"> Done</button>
    

D) Two-way Binding : Two-way data binding allows in both ways component to template and voice-versa.

Syntax : [(ngModel)]=”value”

Example :

app.component.ts file

  

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

        @Component({
        selector: 'my-app',
        templateUrl: './app.component.html',
        styleUrls: [ './app.component.css' ]
        })
        export class AppComponent  {
        firstName='John';
        lastName='Doe'

        }

    

app.component.html file

24. What is metadata?

Metadata is used to decorate the class so that it can configure the expected behaviour of a class. Metadata can be attached to the TypeScript using the decorator.

 A) Class decorators : e.g. @NgModule and @Component

  

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

        @Component({
        selector: 'my-app',
        templateUrl: './app.component.html',
        styleUrls: [ './app.component.css' ]
        })
        export class AppComponent  {
        firstName='John';
        lastName='Doe'
        }


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

    

B) Property decorators Used for properties inside component. for example, @Input and @Output

  

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

        @Component({
        selector: 'my-app',
        templateUrl: './app.component.html',
        styleUrls: [ './app.component.css' ]
        })
        export class AppComponent  {
        @Input()    title: string;

        firstName='John';
        lastName='Doe'
        }
    

C) Method decorators: Used for methods inside component class, e.g. @HostListener

  


        @HostListener('click', ['$event'])
        onHostClicked(event: Event) {
        console.log('HostListener event')
        }

        }
    

D) Parameter decorators Used for parameters inside component class constructors, e.g. @Inject

  

        export class AppComponent  {
        constructor(@Inject(Service1) Service1) {
        console.log(Service1);
        }

        }
    

25. What is angular CLI?

The Angular CLI is a command-line interface tool which is used to initialize, develop, scaffold, and maintain Angular applications.

Some of angular command as follows

  • ng new appName : Creating New Project
  • ng generate class class1: add a class to your application
  • ng generate component component1: add a component to your application
  • ng generate directive directive1: add a directive to your application
  • ng generate enum enum1: add an enum to your application
  • ng generate module module1: add a module to your application
  • ng generate pipe pipe1: add a pipe to your application
  • ng generate service service1: add a service to your application
  • ng serve : Run the angular project:

26. What is the difference between constructor and ngOnInit?

constructor ngOnInit

It is a default method of the class that is executed when the class is instantiated.

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

Used for Injecting dependencies

business logic performed

Called by JavaScript engine

Called by angular

 Not everything in component is initialized at the time of invocation

Everything is ready at the time of invocation

No need to import anything

In order to use OnInit we have to import it in the component class like this:
import {Component, OnInit} from '@angular/core';

27. What are the @Component configuration options?

  • selector: The CSS selector that identifies this directive in a template and triggers instantiation of the directive.
  • templateUrl: The relative path or absolute URL of a template file for an Angular component.
  • template: An inline html template for an Angular component.
  • styleUrls: Array of absolute URLs for files containing CSS stylesheets to use in this component.
  • styles: Inline CSS stylesheets.
  • providers: This is an array of dependency injection providers for services that the component requires.

28. What is a service?

A service is used when a common functionality needs to be provided to many modules. The main objective of a service is to organize and share business logic, data, models and functions with different components of an Angular application.

  

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

        @Injectable()
        export class GreetingService {

        constructor() { }

        public sayHello(){
        console.log('Hello John Doe')
        }

        }
    

29. What is @Injectable() services?

Angular Injectable symbol and annotates the class with the @Injectable() decorator. This marks the class as one that participates in the dependency injection system.

30. How to inject service in root level?

Use  providedIn: 'root' in the @Injectable() to register the service in root level and this service will be  available in all the components.

  

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

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

        constructor() { }

        public sayHello(){
        console.log('Hello John Doe')
        }

        }
    

31. What is dependency injection in Angular?

Dependency Injection (DI) is software design pattern and it is a core concept of Angular which allows a class receive dependencies from another class. In Angular Application, dependency injection is done by injecting a service class into a module or component class.

Service :

  


        @Injectable()
        export class GreetingService {

        constructor() { }

        public sayHello(){
        console.log('Hello John Doe')
        }

        }

    

Component

  

        import { Component ,HostListener } from '@angular/core';
        import {GreetingService} from './greeting.service'

        @Component({
        selector: 'my-app',
        templateUrl: './app.component.html',
        styleUrls: [ './app.component.css' ],
        providers:[GreetingService]
        })
        export class AppComponent  {
        constructor(
        private greetingService:GreetingService
        ) {
        greetingService.sayHello()
        }

        }

    

32. What is the purpose of async pipe?

The async pipe subscribes to an Observable or Promise and returns the latest value it has emitted. When a new value is emitted, the async pipe marks the component to be checked for changes. When the component gets destroyed, the async pipe unsubscribes automatically to avoid potential memory leaks.

  

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

        @Component({
        selector: 'my-app',
        templateUrl: './app.component.html',
        styleUrls: [ './app.component.css' ]

        })
        export class AppComponent  {
        currentNumber: Observable<number>
            constructor( ) {
            }

            ngOnInit() {
            this.currentNumber = Observable.create(observer => {
            let value = 0
            const interval = setInterval(() => {
            observer.next(value)
            value++
            }, 1000)

            return () => clearInterval(interval)
            })
            }
            }
    

  

<h3> Angular Interview Question </h3>

<p>
            Current Numbe is {{currentNumber | async}}
        </p>

    

34. What is the purpose of ngFor directive?

ngFor is a built-in template directive which makes it easy to iterate over an array and display each item of array.

Component

  

        import { Component ,HostListener } from '@angular/core';
        @Component({
        selector: 'my-app',
        templateUrl: './app.component.html',
        styleUrls: [ './app.component.css' ]

        })
        export class AppComponent  {

        numbers= [1,2,3,4,5,6,7,8,8,9];
        constructor( ) {
        }

        }
    

Html Template

  

<ul>
<li *ngFor="let number of numbers">{{ number }}</li>
        </ul>

    

35. What is the purpose of ngIf directive?

NgIf is a built-in directive which adds or removes DOM element depending on if the expression passed to it is true or false.

Component

  

        import { Component ,HostListener } from '@angular/core';
        @Component({
        selector: 'my-app',
        templateUrl: './app.component.html',
        styleUrls: [ './app.component.css' ]

        })
        export class AppComponent  {
        showElement=true
        constructor( ) {
        }
        }

    

HTML template

  

<p *ngIf="showElement">
            Show it when showElement is true
        </p>
    

36. What is the purpose of NgSwitch directive?

ngSwitch  is a structural directive which adds or removes templates when the next match expression matches the switch expression.

Component

  

        import { Component ,HostListener } from '@angular/core';
        @Component({
        selector: 'my-app',
        templateUrl: './app.component.html',
        styleUrls: [ './app.component.css' ]

        })
        export class AppComponent  {

        gender='Male'
        constructor( ) {
        }
        }
    

HTML template

  

<div [ngSwitch]="gender">
<p *ngSwitchCase="'Male'">Male</p>
<p *ngSwitchCase="'Female'">Female</p>
<p *ngSwitchDefault>Not Provided</p>
        </div>


    

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

Angular detect the value as unsafe and automatically sanitizes it and removes the <script> tag but keeps safe content such as the text content of the <script> tag.  It will eliminate the risk of script injection attacks.

38. What is interpolation?

Interpolation is used display a component property in the template with double curly braces{{}} syntax.

  

<h2>Greetings {{ name }}! </h2>
    

39. What are template expressions?

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".

40. What are pipes?

A pipe takes in data as input and transforms it to a desired output.

  

<p>Date of Birth is {{ birthDate | date }}</p>
    

41. What is a parameterized pipe?

A parameter is separated with a colon symbol (:) after the pipe

Syntax : {{value|Pipe1: parameter1: parameter2 }}

  

<p>BirthDate is {{ birthDate | date:'dd/mm/yyyy'}}</p>` // 02/02/2020
    

42. How do you chain pipes?

You can chain multiple pipes together which helps in scenarios where we need to associate more than one pipe that needs to be applied, and the final output will be transformed with all the pipes applied.

  

        `<p>BirthDate is {{  birthDate | date:'fullDate' | uppercase}} </p>` // SUNDAY, FEBRUARY 2, 2020
    

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

impure-pipe:  works for every change in the component

pure-pipe :  works only when the component is loaded.

44. How to make pipe or impure pure?

  

        @Pipe({
        name: 'sort',
        pure: false //true makes it pure and false makes it impure
        })
        export class myPipe implements PipeTransform {

        transform(value: any, args?: any): any {
        //your logic here and return the result
        }

        }
    

45. How to create custom pipe?

  

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

        @Pipe({
        name: 'sum',
        })

        export class Sum implements PipeTransform {

        transform(value:[number]): number  {
        return value.reduce((first, second) => first + second);
        }

        }

        numbers = [1, 2, 3, 4,5, 6];

<h2>Sum  :{{ numbers | sum }} </h2>

    

46. What is a bootstrapping module?

Every Angular application required at least one Angular module, the root module that you bootstrap to launch the application and it is called as bootstrapping module. This module is known as known as AppModule. Angular CLI generate the default AppModule same as below code snippet.

  

        /* JavaScript imports */
        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 { }

    

47. What is observable?

Angular Application uses observable which is implemented with RxJS library to handle a variety of common asynchronous operations. An observable is work as Producer of multiple values which pushing values to subscribers.

  • You can define custom events that send observable output data from a child to a parent component.
  • The HTTP module uses observables to handle AJAX requests and responses.
  • The Router and Forms modules use observables to listen for and respond to user-input events.

48. What is RxJS?

RxJS (Reactive Extensions for JavaScript) is a library for reactive programming using observables that makes it easier to compose asynchronous or callback-based code.

RxJS provides an implementation of the Observable type, which is needed until the type becomes part of the language and until browsers support it. The library also provides utility functions for creating and working with observables. These utility functions can be used for:

  • Converting existing code for async operations into observables
  • Iterating through the values in a stream
  • Mapping values to different types
  • Filtering streams
  • Composing multiple streams

 

import { from } from 'rxjs';

49. What is subscribing?

An Observable instance begins publishing values only when someone subscribes to it. You subscribe by calling the subscribe() method of the instance, passing an observer object to receive the notifications.

  

        import { Component, HostListener } from "@angular/core";
        import { interval } from "rxjs";

        @Component({
        selector: "my-app",
        templateUrl: "./app.component.html",
        styleUrls: ["./app.component.css"]
        })
        export class AppComponent {
        // Create an Observable that will publish a value on an interval
        secondsCounter = interval(1000);
        subscriber:any;

        constructor() {
        this.secondsCounter.subscribe(n => {
        console.log(`It's been ${n} seconds since subscribing!`);
        if (n >= 10) {
        this.subscriber.unsubscribe();
        }
        });


        }
        }
    

50. What is an observer?

Observer is an interface for a consumer of push-based notifications delivered by an Observable.

observer is a consumer of the data which is emitted by observables as a producer.  Observers subscribe to the observables using subscribe() method to consume the data. whenever observables emit  any data, all the registered observers received the data in next() call-back method.

Observer object has three call-back method and these are as follows :

  • next() : This method is used for logic processing and computation. It is required.
  • error() : This method is used to capture any error. It is optional.
  • complete(): This method is used in the last when the process is completed. It is optional.
  

        // Create simple observable that emits three values
        const myObservable = of(1, 2, 3);

        // Create observer object
        const myObserver = {
        next: x => console.log('Observer got a next value: ' + x),
        error: err => console.error('Observer got an error: ' + err),
        complete: () => console.log('Observer got a complete notification'),
        };

        // Execute with the observer object
        myObservable.subscribe(myObserver);
        // Logs:
        // Observer got a next value: 1
        // Observer got a next value: 2
        // Observer got a next value: 3
        // Observer got a complete notification
    

51. What is an Operator?

RxJS provides numerous operators like map(), filter(), concat(), of(), pipe(),  etc. to perform complex manipulation of the collection on the source observables. These Operators are like functions, which takes configuration options, and return a function that takes a source observable.

Some RxJS operators are as follows:

• of() • map() • filter() • from() • concat() • share() • switchMa() Example

  • of()
  • map()
  • filter()
  • from()
  • concat()
  • share()
  • switchMa()

 

Example

  

        import { map } from 'rxjs/operators';

        const nums = of(1, 2, 3);

        const squareValues = map((val: number) => val * val);
        const squaredNums = squareValues(nums);

        squaredNums.subscribe(x => console.log(x));

        // Logs
        // 1
        // 4
        // 9
    

52. What is catchError RxJS operator?

RxJS provides the catchError operator that use to handle errors in the observable recipe.

  

        import { ajax } from 'rxjs/ajax';
        import { map, catchError } from 'rxjs/operators';
        // Return "response" from the API. If an error happens,
        // return an empty array.
        const apiData = ajax('/api/data').pipe(
        map(res => {
        if (!res.response) {
        throw new Error('Value expected!');
        }
        return res.response;
        }),
        catchError(err => of([]))
        );

        apiData.subscribe({
        next(x) { console.log('data: ', x); },
        error(err) { console.log('errors already caught... will not run'); }
        });
    

53. What is multicasting?

Multicasting is the practice of broadcasting to a list of multiple subscribers in a single execution. With a multicasting observable, you don't register multiple listeners on the document, but instead re-use the first listener and send values out to each subscriber.

  


    
function multicastSequenceSubscriber() { const seq = [1, 2, 3]; // Keep track of each observer (one for every active subscription) const observers = []; // Still a single timeoutId because there will only ever be one // set of values being generated, multicasted to each subscriber let timeoutId; // Return the subscriber function (runs when subscribe() // function is invoked) return (observer) => { observers.push(observer); // When this is the first subscription, start the sequence if (observers.length === 1) { timeoutId = doSequence({ next(val) { // Iterate through observers and notify all subscriptions observers.forEach(obs => obs.next(val)); }, complete() { // Notify all complete callbacks observers.slice(0).forEach(obs => obs.complete()); } }, seq, 0); } return { unsubscribe() { // Remove from the observers array so it's no longer notified observers.splice(observers.indexOf(observer), 1); // If there's no more listeners, do cleanup if (observers.length === 0) { clearTimeout(timeoutId); } } }; }; } // Run through an array of numbers, emitting one value // per second until it gets to the end of the array. function doSequence(observer, arr, idx) { return setTimeout(() => { observer.next(arr[idx]); if (idx === arr.length - 1) { observer.complete(); } else { doSequence(observer, arr, ++idx); } }, 1000); } // Create a new Observable that will deliver the above sequence const multicastSequence = new Observable(multicastSequenceSubscriber()); // Subscribe starts the clock, and begins to emit after 1 second multicastSequence.subscribe({ next(num) { console.log('1st subscribe: ' + num); }, complete() { console.log('1st sequence finished.'); } }); // After 1 1/2 seconds, subscribe again (should "miss" the first value). setTimeout(() => { multicastSequence.subscribe({ next(num) { console.log('2nd subscribe: ' + num); }, complete() { console.log('2nd sequence finished.'); } }); }, 1500); // Logs: // (at 1 second): 1st subscribe: 1 // (at 2 seconds): 1st subscribe: 2 // (at 2 seconds): 2nd subscribe: 2 // (at 3 seconds): 1st subscribe: 3 // (at 3 seconds): 1st sequence finished // (at 3 seconds): 2nd subscribe: 3 // (at 3 seconds): 2nd sequence finished

54. What are RxJS subjects?

RxJS subjects are observables which act as observers and provide a platform for data values to be multi-casted to more than one observer. An observable can be defined as a function that returns a stream of data values to one observer over time.

  

        import { Component, HostListener } from "@angular/core";
        import { Subject } from "rxjs";

        @Component({
        selector: "my-app",
        templateUrl: "./app.component.html",
        styleUrls: ["./app.component.css"]
        })
        export class AppComponent {

        subject = new Subject();
        constructor() {

        }

        ngOnInit(){

        this.subject.subscribe({
        next: (data) => console.log('Prints observer Data :  '+ data)
        });
        this.subject.next(1);
        this.subject.next(2);
        }
        }
    

55. What are the Subject types?

There are three types of Subject and these are as follows:

  • Behavior subject
  • Replay subject
  • Async subject

56. What is Behavior subject?

The behavior subject temporarily stores the current data value of any observer declared before it.

Code Sample :

  

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

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

        // create the object of BehaviorSubject with default value 0
        behaviorSubjectObj = new BehaviorSubject(0);

        ngOnInit(): void {

        // subscribe the first subject
        this.behaviorSubjectObj.subscribe({
        next: (data) => console.log('First observer Data : ' + data)
        });

        // send data to subscriber
        this.behaviorSubjectObj.next(1);
        this.behaviorSubjectObj.next(2);

        // subscribe the second subject
        this.behaviorSubjectObj.subscribe({
        next: (data) => console.log('Second observer Data : ' + data)
        });

        this.behaviorSubjectObj.next(3);
        this.behaviorSubjectObj.next(4);
        }
    

Above code snippet log the below output in browser console window.

Angular Interview Qestions

57. What is Replay Subject?

A Replay Subject stores multiple values from the Observable execution and replays them to new subscribers. It’s provides option to choose how many values you want to emit from the last observer.

Code Sample

  

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

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

        // create the object of ReplaySubject  and buffer 2 values for new subscribers
        replaySubjectObj = new ReplaySubject(2);

        ngOnInit(): void {

        // subscribe the first subject
        this.replaySubjectObj.subscribe({
        next: (data) => console.log('First observer Data : ' + data)
        });

        // send data to subscriber
        this.replaySubjectObj.next(1);
        this.replaySubjectObj.next(2);
        this.replaySubjectObj.next(3);
        this.replaySubjectObj.next(4);

        // subscribe the second subject
        this.replaySubjectObj.subscribe({
        next: (data) => console.log('Second observer Data : ' + data)
        });

        this.replaySubjectObj.next(6);
        this.replaySubjectObj.next(7);
        }

        }

    

Above code snippet log the below output in browser console window.

Angular Interview Qestions

58. What is Async Subject?

Async Subject can only execute after a complete method is called.  It’s emits the very current value only when complete method call.

Sample Code:

  

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

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

        // create the object of AsyncSubject  class
        asyncSubjectObj = new AsyncSubject();

        ngOnInit(): void {

        // subscribe the first AsyncSubject
        this.asyncSubjectObj.subscribe({
        next: (data) => console.log('First observer Data : ' + data)
        });

        // send data to subscriber
        this.asyncSubjectObj.next(1);
        this.asyncSubjectObj.next(2);
        this.asyncSubjectObj.next(3);
        this.asyncSubjectObj.next(4);

        // subscribe the second AsyncSubject
        this.asyncSubjectObj.subscribe({
        next: (data) => console.log('Second observer Data : ' + data)
        });

        this.asyncSubjectObj.next(6);
        this.asyncSubjectObj.next(7);

        // call the complete method to send the latest value to subscriber
        this.asyncSubjectObj.complete();
        }

        }

    

Above code snippet log the below output in browser console window.

Async Subject

59. What are angular elements?

Angular elements are Angular components packaged as custom elements and called as  Web Components, a web standard for defining new HTML elements in a framework-agnostic way.

 The Angular Elements library is essentially a bridge between Angular components and custom web elements API. With Angular Elements, custom elements act as hosts for Angular components.

60. What is the browser support of Angular Elements?

Angular elements are supported by following browsers:

  • Chrome
  • Opera
  • Firefox
  • Safari

Note: Others browser supported through  polyfills.

61. What are custom elements?

Custom elements are reusable, encapsulated HTML tags to use in web applications. It can be used in any framework or library that uses HTML. In short, you are able to create custom DOM elements that have their own functionalities that the rest of the page does not need to know anything about it.  

To create a custom element, you simply need to create an ES6 class that extends from an HTML element and register that class with the browser through an API called the CustomElementRegistry. Custom elements have lifecycle hooks, such as the connectedCallback and the disconnectedCallback.

62. Explain how custom elements works internally?

Below are the steps in an order about custom elements functionality,

 

  • App registers custom element with browser: Use the createCustomElement() function to convert a component into a class that can be registered with the browser as a custom element.
  • App adds custom element to DOM: Add custom element just like a built-in HTML element directly into the DOM.
  • Browser instantiate component based class: Browser creates an instance of the registered class and adds it to the DOM.
  • Instance provides content with data binding and change detection: The content within template is rendered using the component and DOM data.

 

The flow chart of the custom element’s functionality would be as follows

how custom elements works internally

63. How to transfer components to custom elements?

Transforming components to custom elements involves two major steps,

  • Build custom element class: Angular provides the createCustomElement() function for converting an Angular component (along with its dependencies) to a custom element. The conversion process implements NgElementConstructor interface, and creates a constructor class which is used to produce a self-bootstrapping instance of Angular component.
  • Register element class with browser: It uses customElements.define() JS function, to register the configured constructor and its associated custom-element tag with the browser's CustomElementRegistry. When the browser encounters the tag for the registered element, it uses the constructor to create a custom-element instance.

The detailed structure would be as follows,

how custom elements works internally

64. What is Angular Router?

The angular router enables navigation from one view to the next view so that users can perform tasks.

65. What is the purpose of base href tag?

This tag required to routing application which should add element in index.html as the first child to indicate to compose other URL of application. Below is the snippet to set the href value as below

<base href=”/”>

66. What are the router imports?

Angular Router represents a particular component view for a given URL which is not part of Angular Core. This is available in @angular/router library to import required router components. Below is the snippet for the same.

import { RouterModule, Routes } from '@angular/router';

67. What is router outlet?

The RouterOutlet is a directive from the router library and it acts as a placeholder that marks the spot in the template where the router should display the components for that outlet. Router outlet is used like a component,

The RouterOutlet is a directive which is available in the router library and it is used like a component. It acts as a placeholder that marks the spot in the template where the router should display the components for that outlet.

<router-outlet></router-outlet>
<!-- Routed components go here -->

The RouterLink is a directive on the anchor tags give the router control over those elements. The navigation paths are fixed, so you can assign a string value to the routerLink.

  

<h1>Angular Router Links</h1>
<nav>
<a routerLink="/list">List</a>
<a routerLink="/ detail">Detail</a>
        </nav>
<router-outlet></router-outlet>
    

The RouterLinkActive directive toggles css classes for active RouterLink bindings based on the current RouterState. Router will add the one or more classes when link is active.

  

<h1>Angular Router Link</h1>
<nav>
<a routerLink="/list" routerLinkActive="active">List</a>
<a routerLink="/detail" routerLinkActive="active">Detail</a>
        </nav>
<router-outlet></router-outlet>
    

70. What is router state?

RouterState is a tree of activated routes. Every node in this tree knows about the "consumed" URL segments, the extracted parameters, and the resolved data. You can access the current RouterState from anywhere in the application using the Router service and the routerState property.

  

        @Component({templateUrl:'template.html'})
        class MyComponent {
        constructor(router: Router) {
        const state: RouterState = router.routerState;
        const root: ActivatedRoute = state.root;
        const child = root.firstChild;
        const id: Observable<string>
            = child.params.map(p => p.id);
            //...
            }
            }
    

71. What is activated route?

Activate route provides access to information about a route associated with a component that is loaded in an outlet. Use to traverse the RouterState tree and extract information from nodes. The ActivatedRoute will be injected as a router service to access the information like path, parameters etc.

  

        import {ActivatedRoute} from '@angular/router';

        @Component({
        /* . . . */
        })
        export class ActivatedRouteComponent {
        constructor(route: ActivatedRoute) {
        const id: Observable<string>
            = route.params.pipe(map(p => p.id));
            const url: Observable<string>
                = route.url.pipe(map(segments => segments.join('')));
                // route.data includes both `data` and `resolve`
                const user = route.data.pipe(map(d => d.user));
                }
                }
    

72. What is the purpose of Wildcard route?

If the URL does not match any predefined routes then router will throw an error and crash the app. You can use wildcard route to avoid this error. A wildcard route has a path consisting of two asterisks to match every URL and navigate to the configured route. For example, you can define PageNotFoundComponent for wildcard route if routes not configured.

   { path: '**', component: PageNotFoundComponent }

73. How do you define routes?

A router must be configured with a array of route definitions. You configure the router with routes via the RouterModule.forRoot() method and import the routing module in your module like he AppModule's imports array.

See the below code snippet:

  

        import { NgModule }             from '@angular/core';
        import { BrowserModule }        from '@angular/platform-browser';
        import { FormsModule }          from '@angular/forms';
        import { RouterModule, Routes } from '@angular/router';

        import { AppComponent }          from './app.component';
        import { CrisisListComponent }   from './crisis-list/crisis-list.component';
        import { HeroListComponent }     from './hero-list/hero-list.component';

        const appRoutes: Routes = [
        { path: 'crisis-center', component: CrisisListComponent },
        { path: 'heroes', component: HeroListComponent },
        ];

        @NgModule({
        imports: [
        BrowserModule,
        FormsModule,
        RouterModule.forRoot(
        appRoutes,
        { enableTracing: true } // <-- debugging purposes only
                                       )
                                       ],
                                       declarations: [
                                       AppComponent,
                                       HeroListComponent,
                                       CrisisListComponent,
                                       ],
                                       bootstrap: [ AppComponent ]
                                       })
                                       export class AppModule { }
    

74. Do you need a Routing Module?

No, the Routing Module is a design choice. You can skip routing Module (for example, AppRoutingModule) when the configuration is simple and merge the routing configuration directly into the companion module (for example, AppModule). But it is recommended when the configuration is complex and includes specialized guard and resolver services.

75. What are the advantages of Routing module?

  • Separates routing concerns from other application concerns.
  • Provides a module to replace or remove when testing the application.
  • Provides a well-known location for routing service providers including guards and resolvers.
  • Does not declare components.

76. What is ParamMap in angular?

A map that provides access to the required and optional parameters specific to a route. The map supports retrieving a single value with get() or multiple values with getAll() .

  

        interface ParamMap {
        keys: string[]
        has(name: string): boolean
        get(name: string): string | null
        getAll(name: string): string[]
        }
    

77. What is the difference between ActivatedRoute and RouterState/ ActivatedRouteSnapshot?

ActivatedRoute

RouterState/ ActivatedRouteSnapshot

It is observables

It is not observables

Required subscribe

Subscribe not required

Unsubscribe in OnDestroy to prevent memory leak

Unsubscribe not required.

Get the changed value

Change value not updated

It is not immutable object

immutable object representing a particular version of ActivatedRoute

78. Why route parameters are observables?

The reason that the params property on ActivatedRoute is an Observable is that the router may not recreate the component when navigating to the same component. In this case the parameter may change without the component being recreated. View examples running in full screen mode to see route changes in the URL.

79. How can you register routes?

Define an array of routes,  and pass them to the RouterModule.forRoot() method. It returns a module, containing the configured Router service provider and other providers that the routing library requires.

  

        import { NgModule }             from '@angular/core';
        import { BrowserModule }        from '@angular/platform-browser';
        import { FormsModule }          from '@angular/forms';
        import { RouterModule, Routes } from '@angular/router';

        import { AppComponent }          from './app.component';
        import { CrisisListComponent }   from './crisis-list/crisis-list.component';
        import { HeroListComponent }     from './hero-list/hero-list.component';

        const appRoutes: Routes = [
        { path: 'crisis-center', component: CrisisListComponent },
        { path: 'heroes', component: HeroListComponent },
        ];

        @NgModule({
        imports: [
        BrowserModule,
        FormsModule,
        RouterModule.forRoot(
        appRoutes,
        { enableTracing: true } // <-- debugging purposes only
                                       )
                                       ],
                                       declarations: [
                                       AppComponent,
                                       HeroListComponent,
                                       CrisisListComponent,
                                       ],
                                       bootstrap: [ AppComponent ]
                                       })
                                       export class AppModule { }

    

80. How to configure Route with parameters?

{ path: 'detail/:id', component: DetailComponent }

 

In the above code snippet, :id is in the path is used to creates a slot in the path for a Route Parameter.

RouterLink parameters array has two items: the routing path and a route parameter

<a [routerLink]="['/hero', hero.id]">

82. How to navigate to some route from ts file?

You can use nagivate method of router service to navigate to any routes. See the below code snippet for same.

  

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

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

        constructor(private router: Router

        ) { }

        ngOnInit() {
        }

        onNavigate() {
        this.router.navigate(['/product-detail'], { queryParams: { id: 10 } });
        }

        }
<button (click)="onNavigate()">  Navigate to Detail</button>

    

It will navigate the below URL.

http://localhost:4200/product-detail?id=10

83. List out the router events?

The sequence of router events is as follows:

  • NavigationStart
  • RouteConfigLoadStart
  • RouteConfigLoadEnd
  • RoutesRecognized
  • GuardsCheckStart
  • ChildActivationStart
  • ActivationStart
  • GuardsCheckEnd
  • ResolveStart
  • ResolveEnd
  • ActivationEnd
  • ChildActivationEnd
  • NavigationEnd
  • NavigationCancel
  • NavigationError
  • Scroll

84. What are observable creation functions?

RxJS provides creation functions for the process of creating observables from things such as promises, events, timers and Ajax requests. Let us explain each of them with an example,

 Create an observable from a promise

  

        import { from } from 'rxjs'; // from function
        const data = from(fetch('/api/endpoint')); //Created from Promise
        data.subscribe({
        next(response) { console.log(response); },
        error(err) { console.error('Error: ' + err); },
        complete() { console.log('Completed'); }
        });
    

Create an observable that creates an AJAX request

  

        import { ajax } from 'rxjs/ajax'; // ajax function
        const apiData = ajax('/api/data'); // Created from AJAX request
        // Subscribe to create the request
        apiData.subscribe(res => console.log(res.status, res.response));
    

Create an observable from a counter

  

        import { interval } from 'rxjs'; // interval function
        const secondsCounter = interval(1000); // Created from Counter value
        secondsCounter.subscribe(n =>
        console.log(`Counter value: ${n}`));
    

Create an observable from an event

  

        import { fromEvent } from 'rxjs';
        const el = document.getElementById('custom-element');
        const mouseMoves = fromEvent(el, 'mousemove');
        const subscription = mouseMoves.subscribe((e: MouseEvent) => {
        console.log(`Coordnitaes of mouse pointer: ${e.clientX} * ${e.clientY}`);
        });

    

85. What are different types of compilation in Angular?

Angular offers two ways to compile your application,

  • Just-in-Time (JIT)
  • Ahead-of-Time (AOT)

86. What is JIT?

 Just-in-Time (JIT) is a type of compilation that compiles your app in the browser at runtime. JIT compilation is the default when you run the ng build (build only) or ng serve (build and serve locally) CLI commands. Below commands used for JIT compilation,

           ng build       

          ng serve

87. What is AOT?

Ahead-of-Time (AOT) is a type of compilation that compiles your app at build time. For AOT compilation, include the --aot option with the ng build or ng serve command as below,

           ng build --aot       

           ng serve --aot

88. Why do we need compilation process?

The Angular components and templates cannot be understood by the browser directly. Due to that Angular applications require a compilation process before they can run in a browser. For example, In AOT compilation, both Angular HTML and TypeScript code converted into efficient JavaScript code during the build phase before browser runs it.

89. What are the advantages with AOT?

Below is the list of AOT benefits,

  • Faster rendering: The browser downloads a pre-compiled version of the application. So, it can render the application immediately without compiling the app.
  • Fewer asynchronous requests: It in lines external HTML templates and CSS style sheets within the application JavaScript which eliminates separate ajax requests.
  • Smaller Angular framework download size: Doesn't require downloading the Angular compiler. Hence it dramatically reduces the application payload.
  • Detect template errors earlier: Detects and reports template binding errors during the build step itself
  • Better security: It compiles HTML templates and components into JavaScript. So there won't be any injection attacks.

90. Can I use arrow functions in AOT?

Arrow functions or lambda functions can’t be used to assign values to the decorator properties. For example, the following snippet is invalid:

  

        @Component({
        providers: [{
        provide: MyService, useFactory: () => getService()
        }]
        })
    

To fix this, it has to be changed as following exported function:

  

        function getService(){
        return new MyService();
        }

        @Component({
        providers: [{
        provide: MyService, useFactory: getService
        }]
        })
    

91. What is type narrowing?

The expression used in an ngIf directive is used to narrow type unions in the Angular template compiler similar to if expression in typescript. So *ngIf allows the typeScript compiler to infer that the data used in the binding expression will never be undefined.

  

        @Component({
        selector: 'my-component',
        template: '<span *ngIf="user"> {{user.contact.email}} </span>'
        })
        class MyComponent {
        user?: User;
        }
    

92. What are differences between a Promise and an Observable ?

Observable

  1. Emits multiple values over a period of time
  2. Is not called until we subscribe to the Observable
  3. Can be canceled by using the unsubscribe() method
  4. Provides the map, forEach, filter, reduce, retry, and retryWhen operators
  5. possibly asynchronous
  6. Support socket

Promise

  1. Emits only a single value at a time
  2. Calls the services without .then and .catch
  3. Cannot be canceled
  4. Does not provide any operator
  5. Always asynchronous

93. What is dynamic routing?

dynamic route is a route whose path and content is capable of changing depending on the circumstances.

A dynamic route's paths include dynamic segments. A dynamic segment is a placeholder that is filled with different information depending on the circumstances.

For instance, the path in our new dynamic route will look like this:

localhost:4200/albums/:id

Here, :id is the dynamic segment because it will change depending on which Album we're visiting.

this.router.navigate(['albums', clickedAlbum.id]);

94. What are differences between Constructors and OnInit?

Constructors:-

1. The constructor is a default method runs when component is being constructed.
2. The constructor is a typescript feature and it is used only for a class instantiation and nothing to do with Angular
3. The constructor called first time before the ngOnInit().

ngOnInit:-

1. The ngOnInit event is an Angular life-cycle event method that is called after the first ngOnChanges and the ngOnInit method is use to parameters defined with @Input otherwise the constructor is OK.
2. The ngOnInit is called after the constructor and ngOnInit is called after the first ngOnChanges.
3. The ngOnChanges is called when an input or output binding value changes.

95. What is redirectTo in angular?

A URL to which to redirect when a the path matches. Absolute if the URL begins with

  

        [{
        path: 'team/:id',
        component: Team,
        children: [{
        path: 'legacy/user/:name',
        redirectTo: 'user/:name'
        }, {
        path: 'user/:name',
        component: User
        }]
        }]
    

96. What is Empty-path route configurations?

Empty-path route configurations can be used to instantiate components that do not 'consume' any URL segments.

  

        [{
        path: 'team/:id',
        component: Team,
        children: [{
        path: '',
        component: AllUsers
        }, {
        path: 'user/:name',
        component: User
        }]
        }]

    

97. What is Matching Strategy route configurations?

The default path-match strategy is 'prefix', which means that the router checks URL elements from the left to see if the URL matches a specified path.

You can specify the path-match strategy 'full' to make sure that the path covers the whole unconsumed URL. It is important to do this when redirecting empty-path routes. Otherwise, because an empty path is a prefix of any URL, the router would apply the redirect even when navigating to the redirect destination, creating an endless loop.

  

        [{
        path: '',
        pathMatch: 'full',
        redirectTo: 'main'
        }, {
        path: 'main',
        component: Main
        }]
    

98. what is componentless routes in angular?

Componentless routes are useful when the same configurations that will apply to all child routes

  

        [{
        path: 'parent/:id',
        children: [
        { path: 'a', component: MainChild },
        { path: 'b', component: AuxChild, outlet: 'aux' }
        ]
        }]
    

99. what is lazy loading in angular

Lazy loading speeds up application load time by splitting the application into multiple bundles and loading them on demand. To use lazy loading, provide the loadChildren property instead of the children property.

  

        [{
        path: 'lazy',
        loadChildren: () => import('./lazy-route/lazy.module').then(mod => mod.LazyModule),
        }];
    

100. What are some advantages of lazy loading in angular ?

Some advantages of lazy loading as follows:

  • High performance in bootstrap time on initial load.
  • Modules are grouped according to their functionality.
  • Smaller code bundles to download on initial load.
  • Activate/download a code module by navigating to a route.