DEV Community

Alex 👨🏼‍💻FullStack.Cafe
Alex 👨🏼‍💻FullStack.Cafe

Posted on • Updated on • Originally published at fullstack.cafe

22 Expert Angular Interview Questions and Answers in 2018

22 Expert Angular Interview Questions and Answers in 2018
The ultimate list of senior and expert level Angular Interview Questions. Use it to hire a new team member, test yourself, mock your lead dev or completely ignore. Questions sourced from khan4019/angular-interview-questions and answered on FullStack.Cafe.

Originally published on FullStack.Cafe - Never Fail Your Tech Interview Again

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

Topic: Angular
Difficulty: ⭐⭐⭐

  • 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).

🔗 Source: medium.com

Q2: Explain the difference between "Constructor" and "ngOnInit"

Topic: Angular
Difficulty: ⭐⭐⭐

  • 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".

🔗 Source: stackoverflow.com

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

Topic: Angular
Difficulty: ⭐⭐⭐

  • 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<T> - 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.

🔗 Source: ninja-squad.com

Q4: What is AOT?

Topic: Angular
Difficulty: ⭐⭐⭐

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.

🔗 Source: stackoverflow.com

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

Topic: Angular
Difficulty: ⭐⭐⭐⭐

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.

🔗 Source: alligator.io

Q6: What is Zone in Angular?

Topic: Angular
Difficulty: ⭐⭐⭐⭐

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.

🔗 Source: stackoverflow.com

Q7: Why would you use lazy loading modules in Angular app?

Topic: Angular
Difficulty: ⭐⭐⭐⭐

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'
  }
];
Enter fullscreen mode Exit fullscreen mode

🔗 Source: concretepage.com

Q8: What are the lifecycle hooks for components and directives?

Topic: Angular
Difficulty: ⭐⭐⭐⭐

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.

🔗 Source: codecraft.tv

Q9: How would you insert an embedded view from a prepared TemplateRef?

Topic: Angular
Difficulty: ⭐⭐⭐⭐

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'});
    }
}
Enter fullscreen mode Exit fullscreen mode

🔗 Source: stackoverflow.com

Q10: How to detect a route change in Angular?

Topic: Angular
Difficulty: ⭐⭐⭐⭐

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*/ )
    }
}
Enter fullscreen mode Exit fullscreen mode

🔗 Source: medium.com

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

Topic: Angular
Difficulty: ⭐⭐⭐⭐

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.

🔗 Source: stackoverflow.com

Q12: How do you create application to use scss? What changed for Angular 6?

Topic: Angular
Difficulty: ⭐⭐⭐⭐

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

"defaults": {
  "styleExt": "scss",
  "component": {}
}
Enter fullscreen mode Exit fullscreen mode

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"
            }
          }
        }
      }
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

🔗 Source: medium.com

Q13: What is ngUpgrage?

Topic: Angular
Difficulty: ⭐⭐⭐⭐

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.

🔗 Source: blog.nrwl.io

Q14: What is Reactive programming and how does it relate to Angular?

Topic: Angular
Difficulty: ⭐⭐⭐⭐

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.

🔗 Source: github.com/WebPredict

Q15: Name some security best practices in Angular

Topic: Angular
Difficulty: ⭐⭐⭐⭐

  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.

🔗 Source: ordina-jworks.github.io

Q16: Could I use jQuery with Angular?

Topic: Angular
Difficulty: ⭐⭐⭐⭐

First install jQuery using npm as follows

npm install jquery — save
Enter fullscreen mode Exit fullscreen mode

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” ]
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

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");
        });
    });
  }
}
Enter fullscreen mode Exit fullscreen mode

🔗 Source: medium.com

Q17: What is the Angular equivalent to an AngularJS "$watch"?

Topic: Angular
Difficulty: ⭐⭐⭐⭐⭐

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;
  }
}
Enter fullscreen mode Exit fullscreen mode

🔗 Source: medium.com

Q18: Just-in-Time (JiT) vs Ahead-of-Time (AoT) compilation. Explain the difference.

Topic: Angular
Difficulty: ⭐⭐⭐⭐⭐

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.

🔗 Source: stackoverflow.com

Q19: Do you know how you can run angularJS and angular side by side?

Topic: Angular
Difficulty: ⭐⭐⭐⭐⭐

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

🔗 Source: blog.thoughtram.io

Q20: Could you provide some particular examples of using ngZone?

Topic: Angular
Difficulty: ⭐⭐⭐⭐⭐

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 : 
      }
    })
  }
Enter fullscreen mode Exit fullscreen mode
  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";
    })
});
Enter fullscreen mode Exit fullscreen mode

🔗 Source: stackoverflow.com

Q21: Why angular uses url segment?

Topic: Angular
Difficulty: ⭐⭐⭐⭐⭐

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
Enter fullscreen mode Exit fullscreen mode

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
})
Enter fullscreen mode Exit fullscreen mode

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'];
});
Enter fullscreen mode Exit fullscreen mode

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.

🔗 Source: https://stackoverflow.com

Q22: When to use query parameters versus matrix parameters?

Topic: Angular
Difficulty: ⭐⭐⭐⭐⭐


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

🔗 Source: stackoverflow.com

Thanks 🙌 for reading and good luck on your interview!
Check more FullStack Interview Questions & Answers on 👉 www.fullstack.cafe

Top comments (6)

Collapse
 
buildmotion profile image
Matt Vaughn

Question #3: I think we missed the biggest change in the Angular environment. The Workspace is a game-changer -allows for multiple projects in a single environment, including the new Library projects. Sharing and reusing code as libraries is huge, right?

Collapse
 
lucasmonstro profile image
Lucas Silva

One of the best articles I've ever read. U're big!!!

Collapse
 
perjerz profile image
JaMe Siwat Kaolueng

Top last questions seem rare to me. I haven't experienced that kind of scenarios.

Collapse
 
ginoramirezberrios profile image
Gino Ramirez Berrios

👌🏻👏🏻👏🏻👏🏻👏🏻

Collapse
 
sharadjaiswal1411 profile image
PhpScots

Great Set of questions
For full Preparation visit onlineinterviewquestions.com/angul...

Collapse
 
ashinzekene profile image
Ashinze Ekene

This is so informative