FrontendDeveloper.in

Angular Interview Questions

  • Question 241

    What is ngcc?

    The ngcc(Angular Compatibility Compiler) is a tool which upgrades node_module compiled with non-ivy ngc into ivy compliant format. The postinstall script from package.json will make sure your node_modules will be compatible with the Ivy renderer.

    "scripts": {
    "postinstall": "ngcc"
    }
    

    Whereas, Ivy compiler (ngtsc), which compiles Ivy-compatible code.

  • Question 242

    What classes should not be added to declarations?

    The below class types shouldn't be added to declarations

    1. A class which is already declared in any another module.
    2. Directives imported from another module.
    3. Module classes.
    4. Service classes.
    5. Non-Angular classes and objects, such as strings, numbers, functions, entity models, configurations, business logic, and helper classes.
  • Question 243

    What is NgZone?

    Angular provides a service called NgZone which creates a zone named angular to automatically trigger change detection when the following conditions are satisfied.

    1. When a sync or async function is executed.
    2. When there is no microTask scheduled.
  • Question 244

    What is NoopZone?

    Zone is loaded/required by default in Angular applications and it helps Angular to know when to trigger the change detection. This way, it make sures developers focus on application development rather core part of Angular. You can also use Angular without Zone but the change detection need to be implemented on your own and noop zone need to be configured in bootstrap process. Let's follow the below two steps to remove zone.js,

    1. Remove the zone.js import from polyfills.ts.
    /***************************************************************************************************
     * Zone JS is required by default for Angular itself.
     */
    // import 'zone.js/dist/zone';  // Included with Angular CLI.
    
    1. Bootstrap Angular with noop zone in src/main.ts.
    platformBrowserDynamic().bootstrapModule(AppModule, {ngZone: 'noop'})
    .catch(err => console.error(err));
    
  • Question 245

    How do you create displayBlock components?

    By default, Angular CLI creates components in an inline displayed mode(i.e, display:inline). But it is possible to create components with display: block style using displayBlock option,

    ng generate component my-component --displayBlock
    

    (OR) the option can be turned on by default in Angular.json with schematics.@schematics/angular:component.displayBlock key value as true.

  • Question 246

    What are the possible data update scenarios for change detection?

    The change detection works in the following scenarios where the data changes needs to update the application HTML.

    1. Component initialization: While bootstrapping the Angular application, Angular triggers the ApplicationRef.tick() to call change detection and View Rendering.
    2. Event listener: The DOM event listener can update the data in an Angular component and trigger the change detection too.
    @Component({
    selector: 'app-event-listener',
    template: `
    <button (click)="onClick()">Click</button>
    {{message}}`
    })
    export class EventListenerComponent {
    message = '';
    
    onClick() {
    this.message = 'data updated';
    }
    }
    
    1. HTTP Data Request: You can get data from a server through an HTTP request
    data = 'default value';
    constructor(private httpClient: HttpClient) {}
    
    ngOnInit() {
    this.httpClient.get(this.serverUrl).subscribe(response => {
    this.data = response.data; // change detection will happen automatically
    });
    }
    
    1. Macro tasks setTimeout() or setInterval(): You can update the data in the callback function of setTimeout or setInterval
    data = 'default value';
    
    ngOnInit() {
    setTimeout(() => {
    this.data = 'data updated'; // Change detection will happen automatically
    });
    }
    
    1. Micro tasks Promises: You can update the data in the callback function of promise
    data = 'initial value';
    
    ngOnInit() {
    Promise.resolve(1).then(v => {
    this.data = v; // Change detection will happen automatically
    });
    }
    
    1. Async operations like Web sockets and Canvas: The data can be updated asynchronously using WebSocket.onmessage() and Canvas.toBlob().
  • Question 247

    What is a zone context?

    Execution Context is an abstract concept that holds information about the environment within the current code being executed. A zone provides an execution context that persists across asynchronous operations is called as zone context. For example, the zone context will be same in both outside and inside setTimeout callback function,

    zone.run(() => {
    // outside zone
    expect(zoneThis).toBe(zone);
    setTimeout(function() {
    // the same outside zone exist here
    expect(zoneThis).toBe(zone);
    });
    });
    

    The current zone is retrieved through Zone.current.

  • Question 248

    What are the lifecycle hooks of a zone?

    There are four lifecycle hooks for asynchronous operations from zone.js.

    1. onScheduleTask: This hook triggers when a new asynchronous task is scheduled. For example, when you call setTimeout()
    onScheduleTask: function(delegate, curr, target, task) {
    console.log('new task is scheduled:', task.type, task.source);
    return delegate.scheduleTask(target, task);
    }
    
    1. onInvokeTask: This hook triggers when an asynchronous task is about to execute. For example, when the callback of setTimeout() is about to execute.
    onInvokeTask: function(delegate, curr, target, task, applyThis, applyArgs) {
    console.log('task will be invoked:', task.type, task.source);
    return delegate.invokeTask(target, task, applyThis, applyArgs);
    }
    
    1. onHasTask: This hook triggers when the status of one kind of task inside a zone changes from stable(no tasks in the zone) to unstable(a new task is scheduled in the zone) or from unstable to stable.
    onHasTask: function(delegate, curr, target, hasTaskState) {
    console.log('task state changed in the zone:', hasTaskState);
    return delegate.hasTask(target, hasTaskState);
    }
    
    1. onInvoke: This hook triggers when a synchronous function is going to execute in the zone.
    onInvoke: function(delegate, curr, target, callback, applyThis, applyArgs) {
    console.log('the callback will be invoked:', callback);
    return delegate.invoke(target, callback, applyThis, applyArgs);
    }
    
  • Question 249

    What are the methods of NgZone used to control change detection?

    NgZone service provides a run() method that allows you to execute a function inside the angular zone. This function is used to execute third party APIs which are not handled by Zone and trigger change detection automatically at the correct time.

    export class AppComponent implements OnInit {
    constructor(private ngZone: NgZone) {}
    ngOnInit() {
    // use ngZone.run() to make the asynchronous operation in the angular zone
    this.ngZone.run(() => {
    someNewAsyncAPI(() => {
    // update the data of the component
    });
    });
    }
    }
    

    Whereas runOutsideAngular() method is used when you don't want to trigger change detection.

    export class AppComponent implements OnInit {
    constructor(private ngZone: NgZone) {}
    ngOnInit() {
    // Use this method when you know no data will be updated
    this.ngZone.runOutsideAngular(() => {
    setTimeout(() => {
    // update component data and don't trigger change detection
    });
    });
    }
    }
    
  • Question 250

    How do you change the settings of zonejs?

    You can change the settings of zone by configuring them in a separate file and import it just after zonejs import. For example, you can disable the requestAnimationFrame() monkey patch to prevent change detection for no data update as one setting and prevent DOM events(a mousemove or scroll event) to trigger change detection. Let's say the new file named zone-flags.js,

    // disable patching requestAnimationFrame
    (window as any).__Zone_disable_requestAnimationFrame = true;
    
    // disable patching specified eventNames
    (window as any).__zone_symbol__UNPATCHED_EVENTS = ['scroll', 'mousemove'];
    

    The above configuration file can be imported in a polyfill.ts file as below,

    /***************************************************************************************************
     * Zone JS is required by default for Angular.
     */
    import `./zone-flags`;
    import 'zone.js/dist/zone';  // Included with Angular CLI.
    
  • Question 251

    How do you trigger an animation?

    Angular provides a trigger() function for animation in order to collect the states and transitions with a specific animation name, so that you can attach it to the triggering element in the HTML template. This function watch for changes and trigger initiates the actions when a change occurs. For example, let's create trigger named upDown, and attach it to the button element.

    content_copy
    @Component({
    selector: 'app-up-down',
    animations: [
    trigger('upDown', [
    state('up', style({
    height: '200px',
    opacity: 1,
    backgroundColor: 'yellow'
    })),
    state('down', style({
    height: '100px',
    opacity: 0.5,
    backgroundColor: 'green'
    })),
    transition('up => down', [
    animate('1s')
    ]),
    transition('down => up', [
    animate('0.5s')
    ]),
    ]),
    ],
    templateUrl: 'up-down.component.html',
    styleUrls: ['up-down.component.css']
    })
    export class UpDownComponent {
    isUp = true;
    
    toggle() {
    this.isUp = !this.isUp;
    }
    
    
  • Question 252

    How do you configure injectors with providers at different levels?

    You can configure injectors with providers at different levels of your application by setting a metadata value. The configuration can happen in one of three places,

    1. In the @Injectable() decorator for the service itself
    2. In the @NgModule() decorator for an NgModule
    3. In the @Component() decorator for a component
  • Question 253

    Is it mandatory to use injectable on every service class?

    No. The @Injectable() decorator is not strictly required if the class has other Angular decorators on it or does not have any dependencies. But the important thing here is any class that is going to be injected with Angular is decorated. i.e, If we add the decorator, the metadata design:paramtypes is added, and the dependency injection can do it's job. That is the exact reason to add the @Injectable() decorator on a service if this service has some dependencies itself. For example, Let's see the different variations of AppService in a root component,

    1. The below AppService can be injected in AppComponent without any problems. This is because there are no dependency services inside AppService.
    export class AppService {
    constructor() {
    console.log('A new app service');
    }
    }
    
    1. The below AppService with dummy decorator and httpService can be injected in AppComponent without any problems. This is because meta information is generated with dummy decorator.
    function SomeDummyDecorator() {
    return (constructor: Function) => console.log(constructor);
    }
    
    @SomeDummyDecorator()
    export class AppService {
    constructor(http: HttpService) {
    console.log(http);
    }
    }
    

    and the generated javascript code of above service has meta information about HttpService,

    var AppService = (function () {
    function AppService(http) {
    console.log(http);
    }
    AppService = __decorate([
    core_1.Injectable(),
    __metadata('design:paramtypes', [http_service_1.HttpService])
    ], AppService);
    return AppService;
    }());
    exports.AppService = AppService;
    
    1. The below AppService with @injectable decorator and httpService can be injected in AppComponent without any problems. This is because meta information is generated with Injectable decorator.
    @Injectable({
    providedIn: 'root',
    })
    export class AppService {
    constructor(http: HttpService) {
    console.log(http);
    }
    }
    
  • Question 254

    What is an optional dependency?

    The optional dependency is a parameter decorator to be used on constructor parameters, which marks the parameter as being an optional dependency. Due to this, the DI framework provides null if the dependency is not found. For example, If you don't register a logger provider anywhere, the injector sets the value of logger(or logger service) to null in the below class.

    import { Optional } from '@angular/core';
    
    constructor(@Optional() private logger?: Logger) {
    if (this.logger) {
    this.logger.log('This is an optional dependency message');
    } else {
    console.log('The logger is not registered');
    }
    }
    
  • Question 255

    What are the types of injector hierarchies?

    There are two types of injector hierarchies in Angular

    1. ModuleInjector hierarchy: It configure on a module level using an @NgModule() or @Injectable() annotation.
    2. ElementInjector hierarchy: It created implicitly at each DOM element. Also it is empty by default unless you configure it in the providers property on @Directive() or @Component().
Get LinkedIn Premium at Rs 399