Angular interview Questions and Answers Part 3

  1. 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,

    <p *ngIf="user.age > 18">You are not eligible for student pass!</p>

    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.

  2. 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> <b>Syntax</b>';
    }
  3. 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}}
      <img src="{{url}}" style="height:30px">
    </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.

  4. 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 –)

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

  6. 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 direction Syntax Type
    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
  7. What are pipes?

    A pipe takes in data as input and transforms it to 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
    }
  8. 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.

  9. 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);
            }
    
  10. What is a custom pipe?

    Apart from built-inn pipes, you can write your own custom pipe with the below key characteristics,

    1. A pipe is a class decorated with pipe metadata @Pipe decorator, which you import from the core Angular library For example,
        @Pipe({name: 'myCustomPipe'})
    1. The pipe class implements the PipeTransform interface’s transform method that accepts an input value followed by optional parameters and returns the transformed value. The structure of pipeTransform would be as below,
    interface PipeTransform {
      transform(value: any, ...args: any[]): any
    }
    1. The @Pipe decorator allows you to define the pipe name that you’ll use within template expressions. It must be a valid JavaScript identifier.
    template: `{{someInputValue | myCustomPipe: someOtherValue}}`

Leave a Reply