FrontendDeveloper.in

Angular Interview Questions

  • Question 136

    What is platform in Angular?

    A platform is the context in which an Angular application runs. The most common platform for Angular applications is a web browser, but it can also be an operating system for a mobile device, or a web server. The runtime-platform is provided by the @angular/platform-* packages and these packages allow applications that make use of @angular/core and @angular/common to execute in different environments. i.e, Angular can be used as platform-independent framework in different environments, For example,

    1. While running in the browser, it uses platform-browser package.
    2. When SSR(server-side rendering ) is used, it uses platform-server package for providing web server implementation.
  • Question 137

    What happens if I import the same module twice?

    If multiple modules imports the same module then angular evaluates it only once (When it encounters the module first time). It follows this condition even the module appears at any level in a hierarchy of imported NgModules.

  • Question 138

    How do you select an element with in a component template?

    You can use @ViewChild directive to access elements in the view directly. Let's take input element with a reference,

    <input #uname>
    

    and define view child directive and access it in ngAfterViewInit lifecycle hook

    @ViewChild('uname') input;
    
    ngAfterViewInit() {
    console.log(this.input.nativeElement.value);
    }
    
  • Question 139

    How do you detect route change in Angular?

    In Angular7, you can subscribe to router to detect the changes. The subscription for router events would be as below,

    this.router.events.subscribe((event: Event) => {})
    

    Let's take a simple component to detect router changes

    import { Component } from '@angular/core';
    import { Router, Event, NavigationStart, NavigationEnd, NavigationError } from '@angular/router';
    
    @Component({
    selector: 'app-root',
    template: `<router-outlet></router-outlet>`
    })
    export class AppComponent {
    
    constructor(private router: Router) {
    
    this.router.events.subscribe((event: Event) => {
    if (event instanceof NavigationStart) {
    // Show loading indicator and perform an action
    }
    
    if (event instanceof NavigationEnd) {
    // Hide loading indicator and perform an action
    }
    
    if (event instanceof NavigationError) {
    // Hide loading indicator and perform an action
    console.log(event.error); // It logs an error for debugging
    }
    });
    }
    }
    
  • Question 140

    How do you pass headers for HTTP client?

    You can directly pass object map for http client or create HttpHeaders class to supply the headers.

    constructor(private _http: HttpClient) {}
    this._http.get('someUrl',{
    headers: {'header1':'value1','header2':'value2'}
    });
    
    (or)
    let headers = new HttpHeaders().set('header1', headerValue1); // create header object
    headers = headers.append('header2', headerValue2); // add a new header, creating a new object
    headers = headers.append('header3', headerValue3); // add another header
    
    let params = new HttpParams().set('param1', value1); // create params object
    params = params.append('param2', value2); // add a new param, creating a new object
    params = params.append('param3', value3); // add another param
    
    return this._http.get<any[]>('someUrl', { headers: headers, params: params })
    
  • Question 141

    What is the purpose of differential loading in CLI?

    From Angular8 release onwards, the applications are built using differential loading strategy from CLI to build two separate bundles as part of your deployed application.

    1. The first build contains ES2015 syntax which takes the advantage of built-in support in modern browsers, ships less polyfills, and results in a smaller bundle size.
    2. The second build contains old ES5 syntax to support older browsers with all necessary polyfills. But this results in a larger bundle size.

    Note: This strategy is used to support multiple browsers but it only load the code that the browser needs.

  • Question 142

    Does Angular support dynamic imports?

    Yes, Angular 8 supports dynamic imports in router configuration. i.e, You can use the import statement for lazy loading the module using loadChildren method and it will be understood by the IDEs(VSCode and WebStorm), webpack, etc. Previously, you have been written as below to lazily load the feature module. By mistake, if you have typo in the module name it still accepts the string and throws an error during build time.

    {path: ‘user’, loadChildren: ‘./users/user.module#UserModulee’},
    

    This problem is resolved by using dynamic imports and IDEs are able to find it during compile time itself.

    {path: ‘user’, loadChildren: () => import(‘./users/user.module’).then(m => m.UserModule)};
    
  • Question 143

    What is lazy loading?

    Lazy loading is one of the most useful concepts of Angular Routing. It helps us to download the web pages in chunks instead of downloading everything in a big bundle. It is used for lazy loading by asynchronously loading the feature module for routing whenever required using the property loadChildren. Let's load both Customer and Order feature modules lazily as below,

    const routes: Routes = [
    {
    path: 'customers',
    loadChildren: () => import('./customers/customers.module').then(module => module.CustomersModule)
    },
    {
    path: 'orders',
    loadChildren: () => import('./orders/orders.module').then(module => module.OrdersModule)
    },
    {
    path: '',
    redirectTo: '',
    pathMatch: 'full'
    }
    ];
    
  • Question 144

    What are workspace APIs?

    Angular 8.0 release introduces Workspace APIs to make it easier for developers to read and modify the angular.json file instead of manually modifying it. Currently, the only supported storage3 format is the JSON-based format used by the Angular CLI. You can enable or add optimization option for build target as below,

    import { NodeJsSyncHost } from '@angular-devkit/core/node';
    import { workspaces } from '@angular-devkit/core';
    
    async function addBuildTargetOption() {
    const host = workspaces.createWorkspaceHost(new NodeJsSyncHost());
    const workspace = await workspaces.readWorkspace('path/to/workspace/directory/', host);
    
    const project = workspace.projects.get('my-app');
    if (!project) {
    throw new Error('my-app does not exist');
    }
    
    const buildTarget = project.targets.get('build');
    if (!buildTarget) {
    throw new Error('build target does not exist');
    }
    
    buildTarget.options.optimization = true;
    
    await workspaces.writeWorkspace(workspace, host);
    }
    
    addBuildTargetOption();
    
  • Question 145

    How do you upgrade angular version?

    The Angular upgrade is quite easier using Angular CLI ng update command as mentioned below. For example, if you upgrade from Angular 7 to 8 then your lazy loaded route imports will be migrated to the new import syntax automatically.

    $ ng update @angular/cli @angular/core
    
  • Question 146

    What is Angular Material?

    Angular Material is a collection of Material Design components for Angular framework following the Material Design spec. You can apply Material Design very easily using Angular Material. The installation can be done through npm or yarn,

    npm install --save @angular/material @angular/cdk @angular/animations
    (OR)
    yarn add @angular/material @angular/cdk @angular/animations
    

    It supports the most recent two versions of all major browsers. The latest version of Angular material is 8.1.1

  • Question 147

    How do you upgrade location service of angularjs?

    If you are using $location service in your old AngularJS application, now you can use LocationUpgradeModule(unified location service) which puts the responsibilities of $location service to Location service in Angular. Let's add this module to AppModule as below,

    // Other imports ...
    import { LocationUpgradeModule } from '@angular/common/upgrade';
    
    @NgModule({
    imports: [
    // Other NgModule imports...
    LocationUpgradeModule.config()
    ]
    })
    export class AppModule {}
    
  • Question 148

    What is NgUpgrade?

    NgUpgrade is a library put together by the Angular team, which you can use in your applications to mix and match AngularJS and Angular components and bridge the AngularJS and Angular dependency injection systems.

  • Question 149

    How do you test Angular application using CLI?

    Angular CLI downloads and install everything needed with the Jasmine Test framework. You just need to run ng test to see the test results. By default this command builds the app in watch mode, and launches the Karma test runner. The output of test results would be as below,

    10% building modules 1/1 modules 0 active
    ...INFO [karma]: Karma v1.7.1 server started at http://0.0.0.0:9876/
    ...INFO [launcher]: Launching browser Chrome ...
    ...INFO [launcher]: Starting browser Chrome
    ...INFO [Chrome ...]: Connected on socket ...
    Chrome ...: Executed 3 of 3 SUCCESS (0.135 secs / 0.205 secs)
    

    Note: A chrome browser also opens and displays the test output in the "Jasmine HTML Reporter".

  • Question 150

    How to use polyfills in Angular application?

    The Angular CLI provides support for polyfills officially. When you create a new project with the ng new command, a src/polyfills.ts configuration file is created as part of your project folder. This file includes the mandatory and many of the optional polyfills as JavaScript import statements. Let's categorize the polyfills,

    1. Mandatory polyfills: These are installed automatically when you create your project with ng new command and the respective import statements enabled in 'src/polyfills.ts' file.
    2. Optional polyfills: You need to install its npm package and then create import statement in 'src/polyfills.ts' file. For example, first you need to install below npm package for adding web animations (optional) polyfill.
    npm install --save web-animations-js
    

    and create import statement in polyfill file.

    import 'web-animations-js';
    
Get LinkedIn Premium at Rs 399