FrontendDeveloper.in

Angular Interview Questions

  • Question 16

    What is a service?

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

    Let's create a repoService which can be used across components,

    import { Injectable } from '@angular/core';
    import { Http } from '@angular/http';
    
    @Injectable({ // The Injectable decorator is required for dependency injection to work
    // providedIn option registers the service with a specific NgModule
    providedIn: 'root',  // This declares the service with the root app (AppModule)
    })
    export class RepoService{
    constructor(private http: Http){
    }
    
    fetchAll(){
    return this.http.get('https://api.github.com/repositories');
    }
    }
    

    The above service uses Http service as a dependency.

  • Question 17

    What is dependency injection in Angular?

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

  • Question 18

    How is Dependency Hierarchy formed?

    Injectors in Angular have rules that can be leveraged to achieve the desired visibility of injectables in your applications. By understanding these rules, you can determine in which NgModule, Component, or Directive you should declare a provider.

    Angular has two injector hierarchies:

    Screenshot

    Module injector

    When angular starts, it creates a root injector where the services will be registered, these are provided via injectable annotation. All services provided in the ng-model property are called providers (if those modules are not lazy-loaded).

    Angular recursively goes through all models which are being used in the application and creates instances for provided services in the root injector. If you provide some service in an eagerly-loaded model, the service will be added to the root injector, which makes it available across the whole application.

    Platform Module

    During application bootstrapping angular creates a few more injectors, above the root injector goes the platform injector, this one is created by the platform browser dynamic function inside the main.ts file, and it provides some platform-specific features like DomSanitizer.

    NullInjector()

    At the very top, the next parent injector in the hierarchy is the NullInjector().The responsibility of this injector is to throw the error if something tries to find dependencies there, unless you've used @Optional() because ultimately, everything ends at the NullInjector() and it returns an error or, in the case of @Optional(), null.

    Screenshot

    ElementInjector

    Angular creates ElementInjector hierarchies implicitly for each DOM element. ElementInjector injector is being created for any tag that matches the angular component, or any tag on which directive is applied, and you can configure it in component and directive annotations inside the provider's property, thus, it creates its own hierarchy likewise the upper one.

    Screenshot

  • Question 19

    What is the purpose of async pipe?

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

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

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

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

    You can store your component's template in one of two places. You can define it inline using the template property, or you can define the template in a separate HTML file and link to it in the component metadata using the @Component decorator's templateUrl property.

    The choice between inline and separate HTML is a matter of taste, circumstances, and organization policy. But normally we use inline template for small portion of code and external template file for bigger views. By default, the Angular CLI generates components with a template file. But you can override that with the below command,

    ng generate component hero -it
    
  • Question 21

    What is the purpose of `*ngFor` directive?

    We use Angular *ngFor directive in the template to display each item in the list. For example, here we can iterate over a list of users:

    <li *ngFor="let user of users">
    {{ user }}
    </li>
    

    The user variable in the *ngFor double-quoted instruction is a template input variable.

  • Question 22

    What is the purpose of `*ngIf` directive?

    Sometimes an app needs to display a view or a portion of a view only under specific circumstances. The Angular *ngIf directive inserts or removes an element based on a truthy/falsy condition. Let's take an example to display a message if the user age is more than 18:

    Note: Angular isn't showing and hiding the message. It is adding and removing the paragraph element from the DOM. That improves performance, especially in the larger projects with many data bindings.

  • Question 23

    What happens if you use script tag inside template?

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

    Let's take an example of innerHtml property binding which causes XSS vulnerability,

    export class InnerHtmlBindingComponent {
    // For example, a user/attacker-controlled value from a URL.
    htmlSnippet = 'Template <script>alert("0wned")</script> **Syntax**';
    }
    
  • Question 24

    What is interpolation?

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

    Let's take an example,

    <h3>
    {{title}}
    </h3>
    

    In the example above, Angular evaluates the title and url properties and fills in the blanks, first displaying a bold application title and then a URL.

  • Question 25

    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". In interpolation syntax, the template expression is surrounded by double curly braces. For example, in the below interpolation, the template expression is {{username}},

    <h3>{{username}}, welcome to Angular</h3>
    

    The below javascript expressions are prohibited in template expression

    1. assignments (=, +=, -=, ...)
    2. new
    3. chaining expressions with ; or ,
    4. increment and decrement operators (++ and --)

  • Question 26

    What are template statements?

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

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

    <button (click)="editProfile()">Edit Profile</button>
    

    In the above expression, editProfile is a template statement. The below JavaScript syntax expressions are not allowed.

    1. new
    2. increment and decrement operators, ++ and --
    3. operator assignment, such as += and -=
    4. the bitwise operators | and &
    5. the template expression operators

  • Question 27

    How do you categorize data binding types?

    Binding types can be grouped into three categories distinguished by the direction of data flow. They are listed as below,

    1. From the source-to-view
    2. From view-to-source
    3. View-to-source-to-view

    The possible binding syntax can be tabularized as below,

    Data directionSyntaxType
    From the source-to-view(One-way)1. {{expression}} 2. [target]="expression" 3. bind-target="expression"Interpolation, Property, Attribute, Class, Style
    From view-to-source(One-way)1. (target)="statement" 2. on-target="statement"Event
    View-to-source-to-view(Two-way)1. [(target)]="expression" 2. bindon-target="expression"Two-way
  • Question 28

    What are pipes?

    Pipes are simple functions that use template expressions to accept data as input and transform it into a desired output. For example, let us take a pipe to transform a component's birthday property into a human-friendly date using date pipe.

    import { Component } from '@angular/core';
    
    @Component({
    selector: 'app-birthday',
    template: `<p>Birthday is {{ birthday | date }}</p>`
    })
    export class BirthdayComponent {
    birthday = new Date(1987, 6, 18); // June 18, 1987
    }
    
  • Question 29

    What is a parameterized pipe?

    A pipe can accept any number of optional parameters to fine-tune its output. The parameterized pipe can be created by declaring the pipe name with a colon ( : ) and then the parameter value. If the pipe accepts multiple parameters, separate the values with colons. Let's take a birthday example with a particular format(dd/MM/yyyy):

    import { Component } from '@angular/core';
    
    @Component({
    selector: 'app-birthday',
    template: `<p>Birthday is {{ birthday | date:'dd/MM/yyyy'}}</p>` // 18/06/1987
    })
    export class BirthdayComponent {
    birthday = new Date(1987, 6, 18);
    }
    

    Note: The parameter value can be any valid template expression, such as a string literal or a component property.

  • Question 30

    How do you chain pipes?

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

    import { Component } from '@angular/core';
    
    @Component({
    selector: 'app-birthday',
    template: `<p>Birthday is {{  birthday | date:'fullDate' | uppercase}} </p>` // THURSDAY, JUNE 18, 1987
    })
    export class BirthdayComponent {
    birthday = new Date(1987, 6, 18);
    }
    
    
Get LinkedIn Premium at Rs 399