FrontendDeveloper.in

Angular Interview Questions

Filter by topic:
  • You can use jquery in Angular using 3 simple steps,

    1. Install the dependency: At first, install the jquery dependency using npm
    npm install --save jquery
    
    1. Add the jquery script: In Angular-CLI project, add the relative path to jquery in the angular.json file.
    "scripts": [
    "node_modules/jquery/dist/jquery.min.js"
    ]
    
    1. Start using jquery: Define the element in template. Whereas declare the jquery variable and apply CSS classes on the element.
    <h1>JQuery integration</h1>
    
    import {Component, OnInit} from '@angular/core';
    
    declare var $: any; // (or) import * as $ from 'jquery';
    
    @Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
    })
    export class AppComponent implements OnInit {
    ngOnInit(): void {
    $(document).ready(() => {
    $('#elementId').css({'text-color': 'blue', 'font-size': '150%'});
    });
    }
    }
    
  • This exception is due to missing HttpClientModule in your module. You just need to import in module as below,

    import { HttpClientModule } from '@angular/common/http';
    
    @NgModule({
    imports: [
    BrowserModule,
    HttpClientModule,
    ],
    declarations: [ AppComponent ],
    bootstrap:    [ AppComponent ]
    })
    export class AppModule { }
    
  • The RouteState is an interface which represents the state of the router as a tree of activated routes.

    interface RouterState extends Tree {
    snapshot: RouterStateSnapshot
    toString(): string
    }
    

    You can access the current RouterState from anywhere in the Angular app using the Router service and the routerState property.

  • When you are creating your project with angular cli, you can use ng newcommand. It generates all your components with predefined sass files.

    ng new My_New_Project --style=sass
    

    But if you are changing your existing style in your project then use ng set command,

    ng set defaults.styleExt scss
    
  • The hidden property is used to show or hide the associated DOM element, based on an expression. It can be compared close to ng-show directive in AngularJS. Let's say you want to show user name based on the availability of user using hidden property.

    My name is: {{user.name}}
    
  • The slice pipe is used to create a new Array or String containing a subset (slice) of the elements. The syntax looks like as below,

    {{ value_expression | slice : start [ : end ] }}
    

    For example, you can provide 'hello' list based on a greeting array,

    @Component({
    selector: 'list-pipe',
    template: `<ul>
    <li *ngFor="let i of greeting | slice:0:5">{{i}}</li>
    </ul>`
    })
    export class PipeListComponent {
    greeting: string[] = ['h', 'e', 'l', 'l', 'o', 'm','o', 'r', 'n', 'i', 'n', 'g'];
    }
    
  • The index property of the NgFor directive is used to return the zero-based index of the item in each iteration. You can capture the index in a template input variable and use it in the template.

    For example, you can capture the index in a variable named indexVar and displays it with the todo's name using ngFor directive as below.

  • The main purpose of using *ngFor with trackBy option is performance optimization. Normally if you use NgFor with large data sets, a small change to one item by removing or adding an item, can trigger a cascade of DOM manipulations. In this case, Angular sees only a fresh list of new object references and to replace the old DOM elements with all new DOM elements. You can help Angular to track which items added or removed by providing a trackBy function which takes the index and the current item as arguments and needs to return the unique identifier for this item.

    For example, lets set trackBy to the trackByTodos() method

    ({{todo.id}}) {{todo.name}}
    

    and define the trackByTodos method,

    trackByTodos(index: number, item: Todo): number { return todo.id; }
    
  • NgSwitch directive is similar to JavaScript switch statement which displays one element from among several possible elements, based on a switch condition. In this case only the selected element placed into the DOM. It has been used along with NgSwitch, NgSwitchCase and NgSwitchDefault directives.

    For example, let's display the browser details based on selected browser using ngSwitch directive.

    <chrome-browser    *ngSwitchCase="'chrome'"    [item]="currentBrowser"></chrome-browser>
    <firefox-browser   *ngSwitchCase="'firefox'"     [item]="currentBrowser"></firefox-browser>
    <opera-browser     *ngSwitchCase="'opera'"  [item]="currentBrowser"></opera-browser>
    <safari-browser     *ngSwitchCase="'safari'"   [item]="currentBrowser"></safari-browser>
    <ie-browser  *ngSwitchDefault           [item]="currentItem"></ie-browser>
    
  • Yes, it is possible to do aliasing for inputs and outputs in two ways.

    1. Aliasing in metadata: The inputs and outputs in the metadata aliased using a colon-delimited (:) string with the directive property name on the left and the public alias on the right. i.e. It will be in the format of propertyName:alias.
    inputs: ['input1: buyItem'],
    outputs: ['outputEvent1: completedEvent']
    
    1. Aliasing with @Input()/@Output() decorator: The alias can be specified for the property name by passing the alias name to the @Input()/@Output() decorator.i.e. It will be in the form of @Input(alias) or @Output(alias).
    @Input('buyItem') input1: string;
    @Output('completedEvent') outputEvent1 = new EventEmitter<string>();
    
  • The safe navigation operator(?)(or known as Elvis Operator) is used to guard against null and undefined values in property paths when you are not aware whether a path exists or not. i.e. It returns value of the object path if it exists, else it returns the null value.

    For example, you can access nested properties of a user profile easily without null reference errors as below,

    Using this safe navigation operator, Angular framework stops evaluating the expression when it hits the first null value and renders the view without any errors.

  • You don't need any special configuration. In Angular9, the Ivy renderer is the default Angular compiler. Even though Ivy is available Angular8 itself, you had to configure it in tsconfig.json file as below,

    "angularCompilerOptions": {    "enableIvy": true  }
    
  • Angular 9 provides type safe changes in TestBed API changes by replacing the old get function with the new inject method. Because TestBed.get method is not type-safe. The usage would be as below,

    TestBed.get(ChangeDetectorRef) // returns any. It is deprecated now.
    
    TestBed.inject(ChangeDetectorRef) // returns ChangeDetectorRef
    
  • In Angular 8, the static flag is required for ViewChild. Whereas in Angular9, you no longer need to pass this property. Once you updated to Angular9 using ng update, the migration will remove { static: false } script everywhere.

    @ViewChild(ChildDirective) child: ChildDirective; // Angular9 usage
    @ViewChild(ChildDirective, { static: false }) child: ChildDirective; //Angular8 usage