All interview topics
Full-Stack, Web & Mobile

Angular Interview Questions and Answers

Practice Angular interview questions and answers organized by difficulty, with revealable explanations and related topics.

112 questionsEntry → Expert

Entry questions

3 questions
  1. Question 1
    Entry

    What is a Module , and what does it contain?

    • Angular
    Reveal answer

    An Angular module is set of Angular basic building blocks like component, directives, services etc. An app can have more than one module. A module can be created using @NgModule decorator.

    @NgModule({
      imports: [ BrowserModule ],
      declarations: [ AppComponent ],
      bootstrap: [ AppComponent ]
    })
    export class AppModule { }
    
  2. Question 2
    Entry

    What are Pipes? Give me an example.

    • Angular
    Reveal answer

    A pipe takes in data as input and transforms it to a desired output. You can chain pipes together in potentially useful combinations. You can write your own custom pipes. Angular comes with a stock of pipes such as DatePipe , UpperCasePipe , LowerCasePipe , CurrencyPipe , and PercentPipe . Consider:

    <p>The hero's birthday is {{ birthday | date }}</p>
    

    In this page, you'll use pipes to transform a component's birthday property into a human-friendly date.

  3. Question 3
    Entry

    What is Routing Guard in Angular?

    • Angular
    Reveal answer

    Angular’s route guards are interfaces which can tell the router **whether or not it should allow navigation **to a requested route. They make this decision by looking for a true or false return value from a class whichimplements the given guard interface. There are five different types of guards and each of them is called in a particular sequence. The router’s behavior is modified differently depending on which guard is used. The guards are:

    CanActivate CanActivateChild CanDeactivate CanLoad Resolve Consider:

    import { Injectable } from '@angular/core';
    import { Router, CanActivate } from '@angular/router';
    import { AuthService } from './auth.service';
    @Injectable()
    export class AuthGuardService implements CanActivate {
      constructor(public auth: AuthService, public router: Router) {}
      canActivate(): boolean {
        if (!this.auth.isAuthenticated()) {
          this.router.navigate(['login']);
          return false;
        }
      return true;
    }
    }
    

Junior questions

20 questions
  1. Question 1
    Junior

    How would you run unit test?

    • Angular
    Reveal answer

    The Angular CLI downloads and install everything you need to test an Angular application with the Jasmine test framework. The project you create with the CLI is immediately ready to test. Just run this one CLI command: ng test

  2. Question 1
    Junior

    You have an HTML response I want to display. How do I do that?

    • Angular
    Reveal answer

    The correct syntax is the following:

    <div [innerHTML]="theHtmlString"></div>
    

    Working in 5.2.6

  3. Question 2
    Junior

    What is the equivalent of ngShow and ngHide in Angular?

    • Angular
    Reveal answer

    Just bind to the hidden property:

    [hidden]="!myVar"
    
  4. Question 3
    Junior

    What is the difference between *ngIf vs [hidden] ?

    • Angular
    Reveal answer
    *ngIf effectively removes its content from the DOM while [hidden] modifies the display property and only
    

    instructs the browser to not show the content but the DOM still contains it.

  5. Question 5
    Junior

    What is Interpolation?

    • Angular
    Reveal answer

    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,

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

  6. Question 6
    Junior

    What is a bootstrapping module?

    • Angular
    Reveal answer

    Every application has at least one Angular module, the root module that you bootstrap to launch the application is called as bootstrapping module. It is commonly known as AppModule . The default structure of AppModule generated by AngularCLI would be as follows:

    /* JavaScript imports */
    import {
      BrowserModule
    } from '@angular/platform-browser';
    import {
      NgModule
    } from '@angular/core';
    import {
      FormsModule
    } from '@angular/forms';
    import {
      HttpClientModule
    } from '@angular/common/http';
    import {
      AppComponent
    } from './app.component';/* the AppModule class with the @NgModule decorator */
    @NgModule({
      declarations: [
      AppComponent
    ],
    imports: [
    BrowserModule,
    FormsModule,
    HttpClientModule
    ],
    providers: [],
    bootstrap: [AppComponent]
    })
    export class AppModule {}
    
  7. Question 7
    Junior

    What are Observable s?

    • Angular
    Reveal answer

    Observables are declarative which provide support for passing messages between publishers and subscribers in your application. They are mainly used for event handling, asynchronous programming, and handling multiple values. In this case, you define a function for publishing values, but it is not executed until a consumer subscribes to it. The

    subscribed consumer then receives notifications until the function completes, or until they unsubscribe.

  8. Question 8
    Junior

    What is an Observable ?

    • Angular
    Reveal answer

    An Observable is a unique Object similar to a Promise that can help manage async code. Observables are not part of the JavaScript language so we need to rely on a popular Observable library called RxJS. The observables are created using new keyword. Let see the simple example of observable,

    import { Observable } from 'rxjs';
    const observable = new Observable(observer => {
      setTimeout(() => {
        observer.next('Hello from a Observable!');
      }, 2000);
    });`
    
  9. Question 9
    Junior

    What is an Observer ?

    • Angular
    Reveal answer

    Observer is an interface for a consumer of push-based notifications delivered by an Observable . It has below structure,

    interface Observer<T> {
      closed?: boolean;
      next: (value: T) => void;
      error: (err: any) => void;
      complete: () => void;
    }
    

    A handler that implements the Observer interface for receiving observable notifications will be passed as a parameter for observable as below,

    myObservable.subscribe(myObserver);
    

    Note: If you don't supply a handler for a notification type, the observer ignores notifications of that type.

  10. Question 10
    Junior

    What is the purpose of base href tag?

    • Angular
    Reveal answer

    The routing application should add element to the index.html as the first child in the tag inorder to indicate how to compose navigation URLs. If app folder is the application root then you can set the href value as below

    <base href="/">
    
  11. Question 11
    Junior

    What is the difference between Structural and Attribute directives in Angular?

    • Angular
    Reveal answer

    Structural directives are used to alter the DOM layout by removing and adding DOM elements. It is far better in changing the structure of the view. Examples of Structural directives are NgFor and Nglf . Attribute Directives These are being used as characteristics of elements. For example, a directive such as built-in NgStyle in the template Syntax guide is an attribute directive.

  12. Question 12
    Junior

    How would you run unit test?

    • Angular
    Reveal answer

    The Angular CLI downloads and install everything you need to test an Angular application with the Jasmine test framework. The project you create with the CLI is immediately ready to test. Just run this one CLI command: ng test

  13. Question 13
    Junior

    How would you protect a component being activated through the router?

    • Angular
    Reveal answer

    The Angular router ships with a feature called guards. These provide us with ways to control the flow of our application. We can stop a user from visitng certain routes, stop a user from leaving routes, and more. The overall process for protecting Angular routes: Create a guard service: ng g guard auth

    Create canActivate ()
    or canActivateChild () methods
    

    Use the guard when defining routes

    // import the newly created AuthGuard
    const routes: Routes = [
    {
      path: 'account',
      canActivate: [AuthGuard]
    }
    ];
    
    Some other available guards:
    CanActivate : Check if a user has access
    

    CanActivateChild : Check if a user has access to any of the child routes CanDeactivate : Can a user leave a page? For example, they haven't finished editing a post Resolve : Grab data before the route is instantiated CanLoad : Check to see if we can load the routes assets

  14. Question 14
    Junior

    What is the difference between @Component and @Directive in Angular?

    • Angular
    Reveal answer

    Directives add behaviour to an existing DOM element or an existing component instance. A component, rather than adding/modifying behaviour, actually creates its own view (hierarchy of DOM elements) with attached behaviour. Write a component when you want to create a reusable set of DOM elements of UI with custom behaviour. Write a directive when you want to write reusable behaviour to supplement existing DOM elements.

  15. Question 15
    Junior

    How can I select an element in a component template?

    • Angular
    Reveal answer

    You can get a handle to the DOM element via ElementRef by injecting it into your component's constructor:

    constructor(myElement: ElementRef) { ... }
    
  16. Question 16
    Junior

    What is a Service, and when will you use it?

    • Angular
    Reveal answer

    Angular services are singleton objects which get instantiated only once during the lifetime of an application. They contain methods that maintain data throughout the life of an application, i.e. data does not get refreshed and is available all the time. The main objective of a service is to organize and share business logic, models, or data and functions with different components of an Angular application. The separation of concerns is the main reason why Angular services came into existence. An Angular service is a stateless object and provides some very useful functions.

  17. Question 17
    Junior

    What's the difference between an Angular Component and Module ?

    • Angular
    Reveal answer

    Components control views ( html ). They also communicate with other components and services to bring functionality to your app. Modules consist of one or more components. They do not control any html. Your modules declare which components can be used by components belonging to other modules, which classes will be injected by the dependency injector and which component gets bootstrapped. Modules allow you to manage your components to bring modularity to your app.

  18. Question 18
    Junior

    What is the minimum definition of a Component ?

    • Angular
    Reveal answer

    The absolute minimal configuration for a @Component in Angular is a template. Both template properties are set to optional because you have to define either template or templateUrl . When you don't define them, you will get an exception like this: No template specified for component 'ComponentName' A selector property is not required, as you can also use your components in a route.

  19. Question 19
    Junior

    What is a Component ? Why would you use it?

    • Angular
    Reveal answer

    Components are the most basic building block of an UI in an Angular application. An Angular application is a tree of Angular components. Angular components are a subset of directives. Unlike directives, components always have a template and only one component can be instantiated per an element in a template. A component must belong to an NgModule in order for it to be usable by another component or application. To specify that a component is a member of an NgModule , you should list it in the declarations field of that NgModule .

    @Component({selector: 'greet', template: 'Hello {{name}}!'})
    class Greet {
      name: string = 'World';
    }
    
  20. Question 20
    Junior

    What are the differences between AngularJS (angular 1.x) and Angular (Angular 2.x and beyond)?

    • Angular
    Reveal answer

    Angular and AngularJS is basically a different framework with the same name.

    Angular is more ready for the current state of web standards and the future state of the web (ES6\7, immutiablity, components, shadow DOM, service workers, mobile compatibilty, modules, typescript and so on and so on... ) Angular killed many main features in AngularJS like - controllers, $scope, directives (replaced with @component annotations), the module definition, and much more, even simple things like ng-repeat has not left the same as it was. Also:

    1. They added an angular cli .
    2. Your angular code is written in ES6 Typescript and it compiles at runtime to Javascript in the browser.
    3. You bind to your HTML similarly like how you would if in an Angular 1 directive. So variable like rootScope have been deprecated. scopeand

Mid questions

41 questions
  1. Question 1
    Mid

    What are dynamic components?

    • Angular
    Reveal answer

    Dynamic components are the components in which components location in the application is not defined at build time .i.e, they are not used in any angular template. But the component is instantiated and placed in the application at runtime.

  2. Question 1
    Mid

    What's new in Angular 6 and why shall we upgrade to it?

    • Angular
    Reveal answer

    Angular Elements - Angular Elements is a project that lets you wrap your Angular components as Web Components and embed them in a non-Angular application. New Rendering Engine: Ivy - increases in speed and decreases in application size. Tree-shakeable providers - a new, recommended, way to register a provider, directly inside the @Injectable() decorator, using the new providedIn attribute RxJS 6 - Angular 6 now uses RxJS 6 internally, and requires you to update your application also. RxJS released a library called rxjs-compat, that allows you to bump RxJS to version 6.0 even if you, or one of the libraries you’re using, is still using one of the “old” syntaxes. ElementRef - in Angular 5.0 or older, is that the said ElementRef had its nativeElement property typed as any. In Angular 6.0, you can now type ElementRef more strictly. Animations - The polyfill web-animations-js is not necessary anymore for animations in Angular 6.0, except if you are using the AnimationBuilder. i18n - possibility to have “runtime i18n”, without having to build the application once per locale.

  3. Question 2
    Mid

    Explain Lazy Loading in Angular?

    • Angular
    Reveal answer

    Lazy loading is one of the most useful concepts of Angular Routing and brings down the size of large files. This is done by lazily loading the files that are required occasionally. Angular 8 comes up with support for dynamic imports in our router configuration. This means that we use the import statement for lazy loading the module and this will be understood by the IDEs, webpack, etc. Angular 7:

    {path: ‘user’, loadChildren: ‘./users/user.module#UserModule’}
    Angular 8:
    {path: ‘user’, loadChildren: () => import(‘./users/user.module’).then(m => m.UserModule)};
    

    New with Angular 8, loadChildren expects a function that uses the dynamic import syntax to import your lazy- loaded module only when it’s needed. As you can see, the dynamic import is promise-based and gives you access to the module, where the module’s class can be called.

  4. Question 2
    Mid

    What is Angular Ivy?

    • Angular
    Reveal answer

    A big part of Angular is its compiler: it takes all your HTML and generates the necessary JS code. This compiler (and the runtime) has been completely rewritten over the last year, and this is what Ivy is about. The last rewrite was done in Angular 4.0. Ivy is a complete rewrite of the compiler (and runtime) in order to: reach better build times (with a more incremental compilation) reach better build sizes (with a generated code more compatible with tree-shaking) unlock new potential features (metaprogramming or higher order components, lazy loading of component instead of modules, a new change detection system not based on zone.js…)

  5. Question 3
    Mid

    What is the option to choose between Inline and External template file?

    • Angular
    Reveal answer

    You can store your component's template in one of two places. You can define it inline using the template property, or

    import {Component} from 'angular2/core';
    @Component({
    
      selector: 'my-app',
      template: `
      <h1>My First Angular 2 multiline template</h1>
      <p>Second line</p>
      `
    })
    export class AppComponent { }
    

    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.

    import {Component} from 'angular2/core';
    @Component({
      selector: 'my-app',
      templateUrl: 'multi-line.html'
    })
    export class AppComponent { }
    

    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

  6. Question 3
    Mid

    How do you categorize data binding types?

    • Angular
    Reveal answer

    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. Question 4
    Mid

    What is Redux and how does it relate to an Angular app?

    • Angular
    Reveal answer

    Redux is a way to manage application state and improve maintainability of asynchronicity in your application by providing a single source of truth for the application state, and a unidirectional flow of data change in the application. ngrx/store is one implementation of Redux principles.

  8. Question 4
    Mid

    What is a Parameterized pipe?

    • Angular
    Reveal answer

    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. The chained hero's birthday is

    {{ birthday | date:'fullDate' | uppercase}}
    
  9. Question 4
    Mid

    Explain the difference between Promise and Observable in Angular?

    • Angular
    Reveal answer

    Promises: return a single value not cancellable more readable code with try/catch and async/await Observables: work with multiple values over time cancellable support map, filter, reduce and similar operators

    use Reactive Extensions (RxJS)
    

    an array whose items arrive asynchronously over time

  10. Question 5
    Mid

    What is Bazel?

    • Angular
    Reveal answer

    Google open sourced the software responsible for building most of its projects under the name Bazel. Bazel is a powerful tool which can keep track of the dependencies between different packages and build targets. Some of the features of Bazel are: It has a smart algorithm for determining the build dependencies - based on the dependency graph of a project, Bazel determines which targets it can build in parallel Bazel is independent of the tech stack. We can build anything we want with it using the same interface. For example, there are plugins for Java, Go, TypeScript, JavaScript, and more

  11. Question 5
    Mid

    How do you perform Error Handling for HttpClient ?

    • Angular
    Reveal answer

    If the request fails on the server or failed to reach the server due to network issues then HttpClient will return an error object instead of a successful reponse. In this case, you need to handle in the component by passing error object as a second callback to subscribe() method. Let's see how it can be handled in the component with an example,

    fetchUser() {
      this.userService.getProfile()
      .subscribe(
      (data: User) => this.userProfile = {
    
        ...data
      },
    // success path
    error => this.error = error
    // error path
    );
    }
    

    It is always a good idea to give the user some meaningful feedback instead of displaying the raw error object returned from HttpClient .

  12. Question 6
    Mid

    What happens if you use <script> tag inside template?

    • Angular
    Reveal answer

    Angular recognizes the value as unsafe and automatically sanitizes it, which removes the tag but keeps safe content such as the text content of the 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>';
    }
    
  13. Question 6
    Mid

    What is the difference between promise and observable ?

    • Angular
    Reveal answer

    Below are the list of differences between promise and observable , Observable Promise Declarative: Computation does not start until subscription so that they can be run whenever you need the result Execute immediately on creation Provide multiple values over time Provide only one Subscribe method is used for error handling which makes centralized and predictable error handling Push errors to the child promises Provides chaining and subscription to handle complex applications Uses only .then() clause

  14. Question 7
    Mid

    What is Subscribing?

    • Angular
    Reveal answer

    An Observable instance begins publishing values only when someone subscribes to it. So you need to subscribe by calling the subscribe() method of the instance, passing an observer object to receive the notifications. Let's take an example of creating and subscribing to a simple observable, with an observer that logs the received message to the console.

    //Creates an observable sequence of 5 integers, starting from 1
    const source = range(1, 5);// Create observer object
    const myObserver = {
      next: x => console.log('Observer got a next value: ' + x),
      error: err => console.error('Observer got an error: ' + err),
      complete: () => console.log('Observer got a complete notification'),
    };// Execute with the observer object and Prints out each item
    myObservable.subscribe(myObserver);
    
    // => Observer got a next value: 1
    // => Observer got a next value: 2
    // => Observer got a next value: 3
    // => Observer got a next value: 4
    // => Observer got a next value: 5
    // => Observer got a complete notification
    
  15. Question 7
    Mid

    What is Multicasting?

    • Angular
    Reveal answer

    Multi-casting is the practice of broadcasting to a list of multiple subscribers in a single execution. Let's demonstrate the multi-casting feature:

    var source = Rx.Observable.from([1, 2, 3]);
    var subject = new Rx.Subject();
    var multicasted = source.multicast(subject);// These are, under the hood, `subject.subscribe({...})`:
    multicasted.subscribe({
      next: (v) => console.log('observerA: ' + v)
    });
    multicasted.subscribe({
      next: (v) => console.log('observerB: ' + v)
    });
    
  16. Question 8
    Mid

    What are the utility functions provided by RxJS?

    • Angular
    Reveal answer

    The RxJS library also provides below utility functions for creating and working with observables.

    1. Converting existing code for async operations into observables
    2. Iterating through the values in a stream
    3. Mapping values to different types
    4. Filtering streams
    5. Composing multiple streams
  17. Question 8
    Mid

    How do you perform error handling in Observable s?

    • Angular
    Reveal answer

    You can handle errors by specifying an error callback on the observer instead of relying on try/catch which are ineffective in asynchronous environment. For example, you can define error callback as below:

    myObservable.subscribe({
      next(num) { console.log('Next num: ' + num)},
      error(err) { console.log('Received an errror: ' + err)}
    });
    
  18. Question 9
    Mid

    What is Router Outlet?

    • Angular
    Reveal answer

    The RouterOutlet is a directive from the router library and it acts as a placeholder that marks the spot in the template where the router should display the components for that outlet. Router outlet is used as a component,

  19. Question 9
    Mid

    What are Custom elements?

    • Angular
    Reveal answer

    Custom elements (or Web Components) are a Web Platform feature which extends HTML by allowing you to define a tag whose content is created and controlled by JavaScript code. The browser maintains a CustomElementRegistry of defined custom elements, which maps an instantiable JavaScript class to an HTML tag. Currently this feature is supported by Chrome, Firefox, Opera, and Safari, and available in other browsers through polyfills.

  20. Question 10
    Mid

    What is Router State?

    • Angular
    Reveal answer

    RouterState is a tree of activated routes. Every node in this tree knows about the "consumed" URL segments, the extracted parameters, and the resolved data. You can access the current RouterState from anywhere in the application using the Router service and the routerState property.

    @Component({
      templateUrl: 'template.html'
    })
    class MyComponent {
      constructor(router: Router) {
        const state: RouterState = router.routerState;
        const root: ActivatedRoute = state.root;
        const child = root.firstChild;
        const id: Observable <string> = child.params.map(p => p.id);
        //...
    
      }
    }
    
  21. Question 10
    Mid

    Explain how Custom Elements works internally?

    • Angular
    Reveal answer

    Below are the steps in an order about custom elements functionality:

    1. App registers custom element with browser: Use the createCustomElement() function to convert a component into a class that can be registered with the browser as a custom element.
    2. App adds custom element to DOM: Add custom element just like a built-in HTML element directly into the DOM.
    3. Browser instantiate component based class: Browser creates an instance of the registered class and adds it to the DOM.
    4. Instance provides content with data binding and change detection: The content with in template is rendered using the component and DOM data.
  22. Question 11
    Mid

    What is Activated route?

    • Angular
    Reveal answer

    ActivatedRoute contains the information about a route associated with a component loaded in an outlet. It can also be used to traverse the router state tree. The ActivatedRoute will be injected as a router service to access the information. In the below example, you can access route path and parameters,

    @Component({
      ...
    })
    class MyComponent {
      constructor(route: ActivatedRoute) {
        const id: Observable < string > = route.params.pipe(map(p => p.id));
        const url: Observable < string > = route.url.pipe(map(segments => segments.join('')));
        // route.data includes both `data` and `resolve`
        const user = route.data.pipe(map(d => d.user));
      }
    }
    
  23. Question 11
    Mid

    What is the difference between @Component and @Directive in Angular?

    • Angular
    Reveal answer

    A @Component requires a view whereas a @Directive does not. Directives I liken a @Directive to an Angular 1.0 directive with the option restrict: 'A' (Directives aren't limited to attribute usage.) Directives add behaviour to an existing DOM element or an existing component instance. One example use case for a directive would be to log a click on an element.

    Components A component, rather than adding/modifying behaviour, actually creates its own view (hierarchy of DOM elements) with attached behaviour. An example use case for this might be a contact card component: Write a component when you want to create a reusable set of DOM elements of UI with custom behaviour. Write a directive when you want to write reusable behaviour to supplement existing DOM elements.

  24. Question 12
    Mid

    What is Angular Universal?

    • Angular
    Reveal answer

    Angular Universal is a server-side rendering module for Angular applications in various scenarios. This is a community driven project and available under @angular/platform-server package. Recently Angular Universal is integrated with Angular CLI.

  25. Question 12
    Mid

    What is the purpose of Wildcard route?

    • Angular
    Reveal answer

    If the URL doesn't match any predefined routes then it causes the router to throw an error and crash the app. In this case, you can use wildcard route. A wildcard route has a path consisting of two asterisks to match every URL. For example, you can define PageNotFoundComponent for wildcard route as below

    { path: '**', component: PageNotFoundComponent }
    
  26. Question 13
    Mid

    Why Incremental DOM has low memory footprint?

    • Angular
    Reveal answer

    Virtual DOM creates a whole tree from scratch every time you rerender. Incremental DOM, on the other hand, doesn’t need any memory to rerender the view if it doesn’t change the DOM. We only have to allocate the memory when the DOM nodes are added or removed. And the size of the allocation is proportional to the size of the DOM change.

  27. Question 13
    Mid

    Do I always need a Routing Module?

    • Angular
    Reveal answer

    No, the Routing Module is a design choice. You can skip routing Module (for example, AppRoutingModule ) when the configuration is simple and merge the routing configuration directly into the companion module (for example, AppModule ). But it is recommended when the configuration is complex and includes specialized guard and resolver services.

  28. Question 14
    Mid

    Explain the difference between Constructor and ngOnInit

    • Angular
    Reveal answer

    The Constructor is a default method of the class that is executed when the class is instantiated and ensures proper initialization of fields in the class and its subclasses. ngOnInit is a life cycle hook called by Angular to indicate that Angular is done creating the component. We have to import OnInit in order to use like this (actually implementing OnInit is not mandatory but considered good practice). Mostly we use ngOnInit for all the initialization/declaration and avoid stuff to work in the constructor. The constructor should only be used to initialize class members but shouldn't do actual "work".

  29. Question 14
    Mid

    What are the ways to control AOT compilation?

    • Angular
    Reveal answer

    You can control your app compilation in two ways

    1. By providing template compiler options in the tsconfig.json file
    2. By configuring Angular metadata with decorators
  30. Question 15
    Mid

    What is AOT?

    • Angular
    Reveal answer

    The Angular Ahead-of-Time compiler pre-compiles application components and their templates during the build process. Apps compiled with AOT launch faster for several reasons. Application components execute immediately, without client-side compilation. Templates are embedded as code within their components so there is no client-side request for template files. You don't download the Angular compiler, which is pretty big on its own. The compiler discards unused Angular directives that a tree-shaking tool can then exclude.

  31. Question 15
    Mid

    When would you use eager module loading?

    • Angular
    Reveal answer

    Eager loading: To load a feature module eagerly we need to import it into application module using imports metadata of @NgModule decorator.

    Eager loading is useful in small size applications. In eager loading, all the feature modules will be loaded before the application starts. Hence the subsequent request to the application will be faster.

  32. Question 16
    Mid

    How would you control size of an element on resize of the window in a component?

    • Angular
    Reveal answer

    @HostListener lets you listen for events on the host element or component. This is a function decorator that accepts an event name as an argument. When that event gets fired on the host element it calls the associated function. Consider:

    @HostListener('window:resize', ['$event'])
    onResize(event: any) {
      this.calculateBodyHeight();
    }
    
  33. Question 16
    Mid

    How to inject base href ?

    • Angular
    Reveal answer

    When building you can modify base tag ( ) in your index.html with --base-href your-url option.

    Sets base tag href to /myUrl/ in your index.html

    ng build --base-href /myUrl/

  34. Question 17
    Mid

    What is Protractor?

    • Angular
    Reveal answer

    Protractor is an end-to-end test framework for Angular and AngularJS applications. Protractor is a Node.js program built on top of WebDriverJS. Protractor runs tests against your application running in a real browser, interacting with it as a user would.

  35. Question 17
    Mid

    What is the use of Codelyzer?

    • Angular
    Reveal answer

    All enterprise applications follows a set of coding conventions and guidelines to maintain code in better way. Codelyzer is an open source tool to run and check whether the pre-defined coding guidelines has been followed or not. Codelyzer does only static code analysis for angular and typescript project. Codelyzer runs on top of tslint and its coding conventions are usually defined in tslint.json file. Codelyzer can be run via angular cli or npm directly. Editors like Visual Studio Code and Atom also supports codelyzer just by doing a basic settings.

  36. Question 18
    Mid

    Why would you use a spy in a test?

    • Angular
    Reveal answer

    Jasmine has a concept called spies . You can check if it was called, what parameters it had, if it returned something or even how many times it was called. Consider:

    it('can accept a post to update it', function() {
      var postToAccept = {
        title: 'Title',
        body: 'Post'
      };
    spyOn(rest, 'update').and.callThrough();
    post.accept(postToAccept);
    expect(rest.update).toHaveBeenCalledWith(postToAccept);
    });
    
  37. Question 18
    Mid

    What is TestBed?

    • Angular
    Reveal answer

    The Angular Test Bed (ATB) is a higher level Angular Only testing framework that allows us to easily test behaviours that depend on the Angular Framework. We still write our tests in Jasmine and run using Karma but we now have a slightly easier way to create components, handle injection, test asynchronous behaviour and interact with our application. The TestBed creates a dynamically-constructed Angular test module that emulates an Angular @NgModule .

  38. Question 19
    Mid

    How to bundle an Angular app for production?

    • Angular
    Reveal answer

    OneTime Setup npm install -g @angular/cli ng new projectFolder creates a new application Bundling Step ng build --prod (run in command line when directory is projectFolder ) flag prod _bundle for production bundles are generated by default to projectFolder/dist/ Deployment You can get a preview of your application using the ng serve --prod command that starts a local HTTP server such that the application with production files is accessible using http://localhost:4200. For a production usage, you have to deploy all the files from the dist folder in the HTTP server of your choice.

  39. Question 19
    Mid

    What is difference between declarations , providers and import in NgModule?

    • Angular
    Reveal answer

    imports makes the exported declarations of other modules available in the current module declarations are to make directives (including components and pipes) from the current module available to other directives in the current module. Selectors of directives, components or pipes are only matched against

    the HTML if they are declared or imported. providers are to make services and values known to DI. They are added to the root scope and they are injected to other services or directives that have them as dependency. A special case for providers are lazy loaded modules that get their own child injector. providers of a lazy loaded module are only provided to this lazy loaded module by default (not the whole application as it is with other modules).

  40. Question 20
    Mid

    Can you explain the difference between Promise and Observable in Angular? In what scenario can we use each case?

    • Angular
    Reveal answer

    Promise

    A Promise handles a single event when an async operation completes or fails. There are Promise libraries out there that support cancellation, but ES6 Promise doesn't so far. Observable An Observable is like a Stream (in many languages) and allows to pass zero or more events where the callback is called for each event. Often Observable is preferred over Promise because it provides the features of Promise and more. With Observable it doesn't matter if you want to handle 0, 1, or multiple events. You can utilize the same API in each case. Observable also has the advantage over Promise to be cancelable. If the result of an HTTP request to a server or some other expensive async operation isn't needed anymore, the Subscription of an Observable allows to cancel the subscription, while a Promise will eventually call the success or failed callback even when you don't need the notification or the result it provides anymore. Observable provides operators like map , forEach , reduce , ... similar to an array There are also powerful operators like retry() , or replay() , ... that are often quite handy.

  41. Question 20
    Mid

    Why should ngOnInit be used, if we already have a constructor ?

    • Angular
    Reveal answer

    The Constructor is a default method of the class that is executed when the class is instantiated and ensures proper initialization of fields in the class and its subclasses. ngOnInit is a life cycle hook called by Angular2 to indicate that Angular is done creating the component. Mostly we use ngOnInit for all the initialization/declaration and avoid stuff to work in the constructor. The constructor should only be used to initialize class members but shouldn't do actual "work". So you should use

    constructor() to setup Dependency Injection and not much else. ngOnInit() is better place to "start" - it's
    

    where/when components' bindings are resolved.

Senior questions

30 questions
  1. Question 1
    Senior

    Could I use jQuery with Angular?

    • Angular
    Reveal answer

    First install jQuery using npm as follows npm install jquery — save Second go to the ./angular-cli.json file at the root of your Angular CLI project folder, and find the scripts: [] property , and include the path to jQuery as follows “scripts”: [ “../node_modules/jquery/dist/jquery.min.js” ] Now to use jQuery anywhere in your application, all you have to do is to import it as follows in app.component.ts file.

    import * as $ from ‘jquery’;
    

    Consider:

    import { Component, OnInit } from '@angular/core';
    import * as $ from 'jquery';
    @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css']
    })
    export class AppComponent implements OnInit {
      title = 'Look jQuery Animation working in action!';
      public ngOnInit()
      {
        $(document).ready(function(){
          $("button").click(function(){
            var div = $("div");
            div.animate({left: '100px'}, "slow");
            div.animate({fontSize: '5em'}, "slow");
          });
      });
    }
    }
    
  2. Question 2
    Senior

    Why we should use Bazel for Angular builds?

    • Angular
    Reveal answer

    Bazel allows us to build at scale. Ideally, the initial build time with Bazel will be comparable to the traditional JavaScript tooling; the difference is that the time will not grow exponentially when our application’s size increases. With Bazel most of the time the build time will stay constant. Many large projects report a significant increase in their incremental builds when their codebase grows. By analyzing the build graph provided by the BUILD.bazel files, Bazel rebuilds only the packages which have changed and nothing else.

  3. Question 3
    Senior

    What is the difference between pure and impure pipe?

    • Angular
    Reveal answer

    A pure pipe is only called when Angular detects a change in the value or the parameters passed to a pipe. For example, any changes to a primitive input value (String, Number, Boolean, Symbol) or a changed object

    reference (Date, Array, Function, Object).
    

    An impure pipe is called for every change detection cycle no matter whether the value or parameters changes. i.e, An impure pipe is called often, as often as every keystroke or mouse-move.

  4. Question 4
    Senior

    What are the advantages with AOT?

    • Angular
    Reveal answer

    Below are the list of AOT benefits,

    1. Faster rendering: The browser downloads a pre-compiled version of the application. So it can render the application immediately without compiling the app.
    2. Fewer asynchronous requests: It inlines external HTML templates and CSS style sheets within the application javascript which eliminates separate ajax requests.
    3. Smaller Angular framework download size: Doesn't require downloading the Angular compiler. Hence it dramatically reduces the application payload.
    4. Detect template errors earlier: Detects and reports template binding errors during the build step itself
    5. Better security: It compiles HTML templates and components into JavaScript. So there won't be any injection attacks.
  5. Question 5
    Senior

    Why would you use lazy loading modules in Angular app?

    • Angular
    Reveal answer

    To load a feature module lazily we need to load it using loadChildren property in route configuration and that feature module must not be imported in application module. Lazy loading is useful when the application size is growing. In lazy loading, feature module will be loaded on demand and hence application start will be faster.

    const routes: Routes = [
    {
      path: 'customers',
      loadChildren: 'app/customers/customers.module#CustomersModule'
    
    },
    {
      path: 'orders',
      loadChildren: 'app/orders/orders.module#OrdersModule'
    },
    {
      path: '',
      redirectTo: '',
      pathMatch: 'full'
    }
    ];
    
  6. Question 5
    Senior

    What is Incremental DOM? How is it different from Virtual DOM?

    • Angular
    Reveal answer

    Incremental DOM is used internally at Google, and it is defined by this key idea:Every component gets compiled into a series of instructions. These instructions create DOM trees and update them in-place when the data changes. React was the first mainstream framework to use** virtual DOM**, which is defined by this key idea:

    Every component creates a new virtual DOM tree every time it gets rerendered. React compares the new virtual DOM tree with the old one and then applies a series of transformations to the browser DOM to match the new virtual DOM tree.

  7. Question 6
    Senior

    What is difference between Incremental DOM and Virtual DOM?

    • Angular React
    Reveal answer

    Incremental DOM is a library for building up DOM trees and updating them in-place when data changes. It differs from the established virtual DOM approach in that no intermediate tree is created (the existing tree is mutated in-place). This approach significantly reduces memory allocation and GC thrashing for incremental updates to the DOM tree therefore increasing performance significantly in some cases. Virtual DOM compares (diff) a new entire virtual DOM with the previous virtual DOM for changes then applies those changes to the actual DOM. - This approach creates a new virtual DOM to determine the

    changes (memory heavy). Has a big memory footprint because it needs headroom for changes that "might"
    

    happen to the virtual DOM.

  8. Question 6
    Senior

    What is Ivy Renderer?

    • Angular
    Reveal answer

    The purpose of Angular view engine is to translate the templates and components that we have written into the regular HTML and JavaScript so it is easy for the browser to read it comfortably. Ivy is the next generation of Angular Renderer. It is third in line after the original compiler (for Angular 2) and Renderer2 (for Angular 4 and above). Angular Ivy is a new Angular renderer, which is radically different from anything we have seen in mainstream frameworks, because it uses incremental DOM.

  9. Question 7
    Senior

    Angular 9: What are some new features in Angular 9?

    • Angular
    Reveal answer

    JavaScript Bundles and Performance - A production build with Angular 8.2.7 resulted in a main.js of 246KB for ES2015 browsers. A build with Angular 9.0.0-next.5 yielded a slightly small main.js file at 214KB. That's a 13 percent improvement from Angular 8. Ivy Compiler - Ivy yields much smaller JavaScript bundles, so Ivy solves Angular’s bundle weaknesses. Selector-less Bindings - Angular ViewEngine already supports this pattern. Still, it was missing in Ivy's initial release Internationalization - You can use the Angular CLI to generate most of the standard code necessary to create files for translators. After you have configured your app to use i18n, you can run the xi18n command to extract the localizable text into a file.

  10. Question 7
    Senior

    Name and explain some Angular Module Loading examples

    • Angular
    Reveal answer

    A module can be loaded eagerly, lazily and preloaded: Eager loading is loading modules before application starts. Lazy loading is loading modules on demand. Preloading is loading modules in background just after application starts. In lazy loading and preloading, modules are loaded asynchronously. The application module i.e. AppModule is loaded eagerly before application starts. But the feature modules can be loaded either eagerly or lazily or preloaded.

  11. Question 8
    Senior

    Explain the purpose of Service Workers in Angular

    • Angular
    Reveal answer

    At its simplest, a service worker is a script that runs in the web browser and manages caching for an application. Service workers function as a network proxy. They intercept all outgoing HTTP requests made by the application and can choose how to respond to them. For example, they can query a local cache and deliver a

    cached response if one is available. Proxying isn't limited to requests made through programmatic APIs, such as fetch; it also includes resources referenced in HTML and even the initial request to index.html. Service worker- based caching is thus completely programmable and doesn't rely on server-specified caching headers. The service worker is preserved after the user closes the tab. The next time that browser loads the application, the service worker loads first, and can intercept every request for resources to load the application. Using a service worker to reduce dependency on the network can significantly improve the user experience.

  12. Question 8
    Senior

    Name some security best practices in Angular

    • Angular
    Reveal answer
    1. To systematically block XSS bugs, Angular treats all values as untrusted by default (sanitation)
    2. Angular templates are the same as executable code: HTML, attributes, and binding expressions (but not the values bound) in templates are trusted to be safe. To prevent these vulnerabilities, use the offline template compiler, also known as template injection.
    3. Avoid interacting with the DOM directly and instead use Angular templates where possible.
    4. Injecting template code into an Angular application is the same as injecting executable code into the application. So, validate all data on server-side code and escape appropriately to prevent XSS vulnerabilities on the server.
    5. Angular HttpClient provides built-in support to prevent XSRF attacks on the client side.
    6. Servers can prevent the XSSI attack by prefixing all JSON responses to make them non-executable, by convention, using the well-known string ")]}',\n" . Angular’s HttpClient library recognizes this convention and automatically strips the string ")]}',\n" from all responses before further parsing.
  13. Question 9
    Senior

    Do I need to bootstrap custom elements?

    • Angular
    Reveal answer

    No, custom elements bootstrap (or start) automatically when they are added to the DOM, and are automatically destroyed when removed from the DOM. Once a custom element is added to the DOM for any page, it looks and behaves like any other HTML element, and does not require any special knowledge of Angular.

  14. Question 9
    Senior

    How would you insert an embedded view from a preparedTemplateRef?

    • Angular
    Reveal answer

    You can create an embedded view using createEmbeddedView method then attach that view to the DOM via TemplateRef :

    @Component({
      selector: 'app-root',
      template: `
      <ng-template #template let-name='fromContext'><div>{{name}}</ng-template>
      `
    })
    export class AppComponent implements AfterViewChecked {
      @ViewChild('template', { read: TemplateRef }) _template: TemplateRef<any>;
      constructor() { }
      ngAfterViewChecked() {
        this.vc.createEmbeddedView(this._template, {fromContext: 'John'});
      }
    }
    
  15. Question 10
    Senior

    What are the mapping rules between Angular component and custom element?

    • Angular
    Reveal answer

    The Component properties and logic maps directly into HTML attributes and the browser's event system. Let us describe them in two steps:

    1. The createCustomElement() API parses the component input properties with corresponding attributes for the custom element. For example, component @Input('myInputProp') converted as custom element attribute my-input-prop .
    2. The Component outputs are dispatched as HTML Custom Events, with the name of the custom event matching the output name. For example, component @Output() valueChanged = new EventEmitter() converted as custom element with dispatch event as valueChanged .
  16. Question 10
    Senior

    What is Zone in Angular?

    • Angular
    Reveal answer

    NgZone is a wrapper around Zone.js which is a library that creates a context around asynchronous functions in order to to make them trackable. Angular's change detection is heavily dependent on Zones.

  17. Question 11
    Senior

    Why do we need compilation process in Angular?

    • Angular
    Reveal answer

    The Angular components and templates cannot be understood by the browser directly. Due to that Angular applications require a compilation process** before they can run in a browser**. For example, In AOT compilation, both Angular HTML and TypeScript code converted into efficient JavaScript code during the build phase before browser runs it.

  18. Question 11
    Senior

    What would be a good use for NgZone service?

    • Angular
    Reveal answer

    The most common use of this service is to optimize performance when starting a work consisting of one or more asynchronous tasks that don't require UI updates or error handling to be handled by Angular. Such tasks can be kicked off via runOutsideAngular and if needed, these tasks can reenter the Angular zone via run.

  19. Question 12
    Senior

    When does a lazy loaded module is loaded?

    • Angular
    Reveal answer

    Lazy loading speeds up the application load time by splitting it into multiple bundles, and loading them on demand, as the user navigates throughout the app. As a result, the initial bundle is much smaller, which improves the bootstrap time. Lazy loading is a technique in Angular that allows you to load JavaScript components asynchronously when a specific route is activated. This can add some initial performance during the initial load, especially if you have many components with complex routing.

  20. Question 12
    Senior

    Are there any pros/cons (especially performance-wise) in using local storage to replace cookie functionality?

    • Angular
    Reveal answer

    Cookies and local storage serve different purposes. Cookies are primarily for reading server-side,

    Local Storage can only be read by the client-side. So the question is, in your app, who needs this data — the client or the server? If it's your client (your JavaScript), then by all means switch to local storage. You're wasting bandwidth by sending all the data in each HTTP header. If it's your server, local storage isn't so useful because you'd have to forward the data along somehow (with Ajax or hidden form fields or something). This might be okay if the server only needs a small subset of the total data for each request.

  21. Question 13
    Senior

    How do you create application to use scss ?

    • Angular
    Reveal answer

    This is how the style config in the CLI v1.x looks like in angular-cli.json file.

    "defaults": {
      "styleExt": "scss",
      "component": {}
    }
    

    But if you take a look into a config schema of angular.json file in version 6, you will no longer find this config anymore. To use SCSS, simply import you scss files (the default value is src/styles.scss ) in your project level in an angular.json file like this.

    {
      ...
      projects: {
        [your_project_name]: {
          ...
          architect: {
            build: {
              ...
              options: {
                styles:{
                  "src/styles.scss"
                }
            }
        }
    }
    }
    }
    }
    
  22. Question 13
    Senior

    How to detect a route change in Angular?

    • Angular
    Reveal answer

    In Angular you can subscribe (Rx event) to a Router instance. So you can do things like:

    class MyClass {
      constructor(private router: Router) {
        router.subscribe((val) =>
        /*whatever*/ )
      }
    }
    
  23. Question 14
    Senior

    What is ngUpgrage ?

    • Angular
    Reveal answer

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

  24. Question 14
    Senior

    What are the lifecycle hooks for components and directives?

    • Angular
    Reveal answer

    A component in Angular has a life-cycle, a number of different phases it goes through from birth to death. We can hook into those different phases to get some pretty fine grained control of our application. constructor This is invoked when Angular creates a component or directive by calling new on the class. ngOnChanges Invoked every time there is a change in one of th input properties of the component. ngOnInit Invoked when given component has been initialized. This hook is only called once after the first ngOnChanges ngDoCheck Invoked when the change detector of the given component is invoked. It allows us to implement our own change detection algorithm for the given component. ngOnDestroy This method will be invoked just before Angular destroys the component. Use this hook to unsubscribe observables and detach event handlers to avoid memory leaks. These hooks are only called for components and not directives. ngAfterContentInit Invoked after Angular performs any content projection into the components view (see the previous lecture on Content Projection for more info). ngAfterContentChecked Invoked each time the content of the given component has been checked by the change detection mechanism of Angular. ngAfterViewInit Invoked when the component’s view has been fully initialized. ngAfterViewChecked Invoked each time the view of the given component has been checked by the change detection mechanism of Angular.

  25. Question 15
    Senior

    What is Reactive Programming and how does it relate to Angular?

    • Angular
    Reveal answer

    Reactive programming is programming with asynchronous data streams. RxJs stands for Reactive Extensions for Javascript, and it's an implementation of Observables for Javascript. An Observable is like a Stream (in many languages) and allows to pass zero or more events where the callback is called for each event. Angular currently uses RxJs Observables in two different ways: as an internal implementation mechanism, to implement some of its core logic like EventEmitter as part of its public API, namely in Forms and the HTTP module You do not need to know Reactive Programming or RxJS in order to build even the most complex applications with Angular. It can however make some types of applications easier to architect.

  26. Question 16
    Senior

    What does a just-in-time (JIT) compiler do (in general)?

    • Angular
    Reveal answer

    A JIT compiler runs after the program has started and compiles the code (usually bytecode or some kind of VM instructions) on the fly (or just-in-time, as it's called) into a form that's usually faster, typically the host CPU's native instruction set. A JIT has access to dynamic runtime information whereas a standard compiler doesn't and can make better optimizations like inlining functions that are used frequently. This is in contrast to a traditional compiler that compiles all the code to machine language before the program is first run.

  27. Question 17
    Senior

    Why would you use renderer methods instead of using native element methods?

    • Angular
    Reveal answer

    Angular is a platform, and the browser is just one option for where we can render our app. When we access the native element directly we are giving up on Angular’s DOM abstraction and miss out on the opportunity to be able to execute also in none-DOM environments such as: native mobile, native desktop, web worker server side rendering. The Renderer2 class is an abstraction provided by Angular in the form of a service that allows to manipulate elements of your app without having to touch the DOM directly. This is the recommended approach because it then makes it easier to develop apps that can be rendered in environments that don’t have DOM access, like on the server, in a web worker or on native mobile.

  28. Question 18
    Senior

    What does detectChanges do in Angular Jasmine tests?

    • Angular
    Reveal answer

    detectChanges propagates changes to the DOM by running Angular change detection.

  29. Question 19
    Senior

    What is the need for SystemJS in Angular?

    • Angular
    Reveal answer

    When tsc compiles typescript into JavaScript, you end up with a bunch of js files on your local system. They somehow need to be loaded into a browser. Since browsers don't support native ES6 module loading yet, you have two options, either put them all into your index.html file in the correct order of dependencies, or you can use a loader to do that all for you. You specify the root for all modules, and then all files are loaded and executed by that loader in the correct order of dependencies. There are many loaders: requirejs , webpack , systemjs and others.

  30. Question 20
    Senior

    How to set headers for every request in Angular?

    • Angular
    Reveal answer

    You could provide a service that wraps the original Http object from Angular.

    import { Injectable } from '@angular/core';
    import { Http, Headers } from '@angular/http';
    @Injectable() export class HttpClient {
      constructor(private http: Http) {}
      createAuthorizationHeader(headers: Headers) {
        headers.append('Authorization', 'Basic ' + btoa('username:password'));
      }
    get(url) {
      let headers = new Headers();
      this.createAuthorizationHeader(headers);
      return this.http.get(url, {
        headers: headers
      });
    }
    post(url, data) {
      let headers = new Headers();
      this.createAuthorizationHeader(headers);
      return this.http.post(url, data, {
        headers: headers
      });
    }
    }
    

    And instead of injecting the Http object you could inject this one ( HttpClient ).

    import { HttpClient } from './http-client';
    

Expert questions

18 questions
  1. Question 1
    Expert

    What is the difference between BehaviorSubject vs Observable ?

    • Angular
    Reveal answer

    BehaviorSubject is a type of subject, a subject is a special type of observable so you can subscribe to messages like any other observable. The unique features of BehaviorSubject are: It needs an initial value as it must always return a value on subscription even if it hasn’t received a next() Upon subscription it returns the last value of the subject. A regular observable only triggers when it receives an onnext at any point you can retrieve the last value of the subject in a non-observable code using the getValue() method. Unique features of a subject compared to an observable are: It is an observer in addition to being an observable so you can also send values to a subject in addition to subscribing to it. In addition you can get an observable from behavior subject using the asobservable() method on BehaviorSubject . In Angular services, I would use BehaviorSubject for a data service as a angular service often initializes before component and behavior subject ensures that the component consuming the service receives the last updated data even if there are no new updates since the component’s subscription to this data.

  2. Question 2
    Expert

    When to use query parameters versus matrix parameters in Url?

    • Angular
    Reveal answer

    Problem

    Query parameters: http://example.com/apples?order=random&color=blue Matrix parameters: http://example.com/apples;order=random;color=blue

    Solution

    The differences between Matrix parameters and Query Parameters are much more than just convention. The main differences are: urls with query params won't have their response cached by intermediaries/proxies (at present) matrix parameters may appear anywhere in path calculating the relative uri is different query params are generally abused to add new verbs instead of using existing methods on resources matrix parameters are not resources, they are aspects that help reference a resource in an information space that is difficult to represent within a hierarchy

  3. Question 2
    Expert

    What is the Angular equivalent to an AngularJS $watch ?

    • Angular
    Reveal answer

    The solution is the set syntax from ES6. The set syntax binds an object property to a function to be called when there is an attempt to set that property.

    import { Component, Input } from '@angular/core';
    @Component({
      selector: 'example-component',
    })
    export class ExampleComponent {
      public internalVal = null;
      constructor() {}
      @Input('externalVal')
      set updateInternalVal(externalVal) {
        this.internalVal = externalVal;
      }
    }
    
  4. Question 3
    Expert

    Is there no equivalent to $scope.emit() or $scope.broadcast() in Angular?

    • Angular
    Reveal answer

    There is no equivalent to $scope.emit() or $scope.broadcast() from AngularJS. EventEmitter inside of a component comes close, but it will only emit an event to the immediate parent component. To communicate between siblings we could use:

    1. Shared Application Model: Siblings can communicate through a shared application model (just like angular 1). For example, when one sibling makes a change to a model, the other sibling that has bindings to the same model is automatically updated.
    2. Component Events: Child components can emit an event to the parent component using @Output() bindings. The parent component can handle the event, and manipulate the application model or it’s own view model. Changes to the Application Model are automatically propagated to all components that directly or indirectly bind to the same model.
    3. Service Events: Components can subscribe to service events. For example, two sibling components can subscribe to the same service event and respond by modifying their respective models. More on this below. To communicate between a Root component and a component nested several levels deep we could use:
    4. Shared Application Model: The application model can be passed from the Root component down to deeply nested sub-components through @Input() bindings. Changes to a model from any component will automatically propagate to all components that share the same model.
    5. Service Events: You can also move the EventEmitter to a shared service, which allows any component to inject the service and subscribe to the event. That way, a Root component can call a service method (typically mutating the model), which in turn emits an event. Several layers down, a grand-child component which has also injected the service and subscribed to the same event, can handle it. Any event handler that changes a shared Application Model, will automatically propagate to all components that depend on it. This is probably the closest equivalent to $scope.broadcast() from Angular 1.
  5. Question 4
    Expert

    Could you provide some particular examples of using ngZone ?

    • Angular
    Reveal answer

    There would be a lot of cases when you want to use NgZone , I can name two:

    1. When you want something to run outside of Angular's change detection. Lets say we want to do some calculation when user is scrolling and don't want you to run change detection, in this case, you'd use NgZone:
    constructor(private zone:NgZone){
      this.zone.runOutsideOfAngular(()=>{
        window.onscroll = ()=>{
          // do some heavy calculation :
        }
    })
    }
    
    1. The exact opposite of above, where you have a function that is somehow outside of Angular's zone and you want it to be inside, like when a third party library is doing some stuff for you and you want it to be bound to your Angular cycle.
    this.zone.run(()=>{
      $.get('someUrl').then(()=>{
        this.myViewVariable = "updated";
      })
    });
    
  6. Question 5
    Expert

    Just-in-Time (JIT) vs Ahead-of-Time (AOT) compilation. Explain the difference.

    • Angular
    Reveal answer

    JIT - Compile TypeScript just in time for executing it: Compiled in the browser. Each file compiled separately. No need to build after changing your code and before reloading the browser page. Suitable for local development. AOT - Compile TypeScript during build phase: Compiled by the machine itself, via the command line (Faster). All code compiled together, inlining HTML/CSS in the scripts. No need to deploy the compiler (Half of Angular size). More secure, original source not disclosed. Suitable for production builds.

  7. Question 6
    Expert

    Do you know how you can run AngularJS and Angular side by side?

    • Angular
    Reveal answer

    In order to run both frameworks side-by-side and make components interoperable, the Angular projects comes with a module ngUpgrade. The module basically acts as an adapter facade, so we don’t really feel that there are two frameworks running side-by-side. For this to work, four things need to interoperate: Dependency Injection - Exposing Angular services into Angular 1.x components and vice-versa. Component Nesting - Angular 1 directives can be used in Angular 2.x components and Angular 2.x components can used Angular 1 directives Content Projection / Transclusion - Angular 1 components transclude Angular 2.x components and Angular 2.x component project Angular 1 directives Change Detection - Angular 1 scope digest and change detectors in Angular >= 2.x are interleaved Here’s what a typical upgrade process would look like:

    Include Angular and upgrade module Pick component to upgrade and change its controller and template Angular 2.x syntax (this is now an

    Angular 2.x component)
    

    Downgrade Angular 2.x component to make it run in Angular 1.x app Pick a service to upgrade, this usually requires little amount of change (especially if we’re on ES2015) Repeat step 2 and 3 (and 4) Replace Angular 1 bootstrap with Angular 2.x bootstrap

  8. Question 7
    Expert

    Why Angular uses Url segment?

    • Angular
    Reveal answer

    A UrlSegment is a part of a URL between the two slashes. It contains a path and the matrix parameters associated with the segment. Matrix parameters are tied to a path segment, while query parameters are tied to the URL. They have different semantics. Consider: localhost:3000/heroes;id=15;foo=foo/bar/baz

    // instead of localhost:3000/heroes/bar/baz?id=15&foo=foo
    

    The parameters are tied to heroes no to the URL. When you access the route.url, you will see this

    this.route.url.subscribe((url: UrlSegment[]) => {
      let heroes = url[0];
      let heroesMatrix = heroes.parameters();
      // heroes should contain id=15, foo=foo
      let bar = url[1].path;
      // 15
      let baz = url[2].path;
      //foo
    })
    

    For matrix parameters you can also subscribe to params instead of peeling them out of url. this.paramSubscription = this.activeRoute.params.subscribe(params => {

    const bar = params['bar'];
    const baz = params['baz'];
    });
    

    With an Angular app, the only people who really care about these parameters are us the developer. The user doesn't care. It is not a REST API where we should stick to well known semantics. For out Angular app, as long as we the developer know how to use params (whether matrix or query), it shouldn't matter which one we use.

  9. Question 8
    Expert

    Why did the Google team go with incremental DOM instead of virtual DOM?

    • Angular
    Reveal answer

    They have one goal in mind: applications have to perform well on mobile devices. This mainly meant optimizing two things: the bundle size and the memory footprint. To achieve the two goals: The rendering engine itself has to be tree shakable The rendering engine has to have low memory footprint

  10. Question 9
    Expert

    Why Incremental DOM is Tree Shakable?

    • Angular
    Reveal answer

    When using incremental DOM, the framework does not interpret the component. Instead, the componentreferences instructions. If it doesn’t reference a particular instruction, it will never be used. And since we know this at compile time, we can omit the unused instruction from the bundle. Virtual DOM requires an interpreter. What part of that interpreter is needed and what part is not isn’t known at compile time, so we have to ship the whole thing to the browser.

  11. Question 10
    Expert

    What is Locality principle for Ivy?

    • Angular
    Reveal answer

    Two main ideas that played a major role when engineering Ivy — locality and tree shaking. Let’s take an example with our PonyComponent that declares its input like this:

    @Input('pony') ponyModel: PonyModel;
    

    When a component uses PonyComponent in its template, it looks like:

    <ns-pony [pony]="myPony"></ns-pony>
    

    The generated code in Ivy looks like:

    // ...
    if (renderFlags & RenderFlags.Update) {
      select(0);
      // updates the public `pony` property
      property('pony', component.myPony);
    }
    },
    directives: [PonyComponent]
    

    But with View Engine, it looked like:

    // ...
    elementDef(0, 'ns-pony'),
    
    // updates the private `ponyModel` field
    directiveDef('PonyComponent', { ponyModel: [0, 'ponyModel'] }
    // ...
    

    This is the locality principle. To compile an AppComponent that uses PonyComponent in its template, Ivy doesn’t need to know anything about the pony component. The output of the Ivy compiler for Appcomponent depends exclusively on the code of AppComponent. That was not true in ViewEngine, where the code generated for the AppComponent also depended on the code of the PonyComponent. It has consequences on the rebuild time as the Ivy compiler can do better than to recompile everything as the View Engine did.

  12. Question 11
    Expert

    Angular 9: Explain improvements in Tree-Shaking

    • Angular
    Reveal answer

    Tree Shaking is performed by both Renderer2 and Ivy. But in some cases suppose, we have imported a function and is hidden by some false conditional, but that function will still get included in the bundle, even though it’s never called for renderer 2. Ivy, on the other hand, breaks things down into smaller, more atomic functions. These atomic functions make the renderer code much more friendly to tree-shaking, because they generate only the code you need from the template you’ve written. As a result you no longer ship the entire framework code, you only bundle pieces of the framework functionality that you use.

  13. Question 12
    Expert

    How Would You Compare View Engine vs Ivy?

    • Angular
    Reveal answer

    View Engine has been introduced with Angular version 4 and still used in version 8, but some limitations have been identified no tree-shakable: both the Hello World application and a very complex one are executed by the same and full runtime. If the internationalization module is not used, for instance, it is part of the runtime anyhow, basically the runtime it cannot be tree-shakable; no incremental compilation: Angular compilation is global and it involves not only the application but also the libraries. Ivy* will the new default rendering engine starting from version 9 and should solve the View Engine current issues:simplify how Angular works internally; tree-shakable the Hello World application does not require the full Angular runtime and will be bundled in only 4.7 KB; incremental compilation is now possible so the compilation is faster than ever and --aot can be now used even during development mode (advice from Angular team).

  14. Question 15
    Expert

    How would you extract webpack config from angular cli project?

    • Angular
    Reveal answer

    We usually use Angular CLI to scaffold our Angular app, but in this case, webpack file is hidden. ng eject was used if you need to do something a lot more advance or custom with webpack than what the cli provides for commands like ng build and ng serve . So it generates a webpack.config.js based on the configurations that the cli uses, so that you can then customize it further. However, that also means that you'll be able to use certain commands like ng build and ng serve . The eject command has been temporarily disabled in Angular 6, as it is not yet compatible with the new angular.json format. The new configuration format provides further flexibility to modify the configuration of your workspace without ejecting. Ejection will be re-enabled in a future release of the CLI. If you need to eject today, use CLI 1.7 to eject your project.

  15. Question 17
    Expert

    Name some differences between SystemJS vs webpack ?

    • Angular Webpack
    Reveal answer

    SystemJS: SystemJS is known to be quirky with dependencies that it uses for its own polyfill Importing libraries/modules from npm is not as simple as it is using WebPack As you add dependencies and the code starts to grow, a fatal flaw of JSPM( systemjs) is revealed. It becomes extremely sluggish. A single refresh can take about 15-20 seconds as the browser will load 100s of different JavaScript files Gulp is still required for: Minification

    Envification (envify)
    

    Generating unique hashname for bundle file WebPack: Changes are now shown in milliseconds; Webpack’s dev server is designed for speed. Not only does it support incremental builds, it serves directly from memory You can easily import libraries from npm (e.g. Bootstrap or Foundation) without worrying about their exact path within node_modules No need of gulp. Webpack itself takes care of doing all the tasks that require Gulp in SystemJS It appears that Webpack was designed from the ground-up for large applications and it shows in the development process

  16. Question 18
    Expert

    What are observable creation functions?

    • Angular
    Reveal answer

    RxJS provides creation functions for the process of creating observables from things such as promises, events, timers and Ajax requests. Let us explain each of them with an example:

    1. Create an observable from a promise
    import { from } from 'rxjs';
    // from function
    const data = from(fetch('/api/endpoint'));
    //Created from Promise
    data.subscribe({
      next(response) { console.log(response); },
      error(err) { console.error('Error: ' + err); },
      complete() { console.log('Completed'); }
    });
    
    1. Create an observable that creates an AJAX request
    import { ajax } from 'rxjs/ajax';
    // ajax function
    const apiData = ajax('/api/data');
    // Created from AJAX request
    // Subscribe to create the request
    apiData.subscribe(res => console.log(res.status, res.response));
    
    1. Create an observable from a counter
    import { interval } from 'rxjs';
    // interval function
    const secondsCounter = interval(1000);
    // Created from Counter value
    secondsCounter.subscribe(n =>
    console.log(`Counter value: ${n}`));
    
    1. Create an observable from an event
    import { fromEvent } from 'rxjs';
    const el = document.getElementById('custom-element');
    const mouseMoves = fromEvent(el, 'mousemove');
    const subscription = mouseMoves.subscribe((e: MouseEvent) => {
      console.log(`Coordnitaes of mouse pointer: ${e.clientX} * ${e.clientY}`);
    });
    
  17. Question 19
    Expert

    How does Ivy affect the (Re)build time?

    • Angular
    Reveal answer

    One of the Ivy goals is to reach better build times (with a more incremental compilation). It's achieved by the new locality principle: To compile an AppComponent that uses AnotherComponent in its template, Ivy doesn’t need to know anything about the pony component. Previously, when you were working on your application, Angular had to recompile everything inside your module to know what had changed, because the generated code of a component could be using internal details of another component. Now each component references the directives and components it uses only by their public APIs. So if you modify an internal detail of a component or a directive, only the actual components that use it will be recompiled! It could lead to huge benefits in rebuild times for applications with dozens of components and directives, as you will go from recompiling all of them to recompile just the needed ones.

  18. Question 20
    Expert

    Angular 8: What are some changes in Location module?

    • Angular
    Reveal answer

    To help people migrating from AngularJS, a bunch of things have been added to the location services in Angular 8. PlatformLocation now offers access to the hostname, port and protocol, and a new getState() method allows to get the history.state . A MockPlatformLocation is also available to ease testing. All this is really useful if you are using ngUpgrade, otherwise you probably won’t need it.