You should know answers for those 14 questions about Angular before your next interview

Tags: angular, webdev, beginners, codenewbie
Published: 2020-08-27 14:52:52

This article was originally published at https://www.blog.duomly.com/angular-interview-questions/

---
### Intro to Angular interview questions

Some time ago, we started a series about [Javascript interview questions](https://www.blog.duomly.com/tags/interview-questions/), we've gone throng some questions about React.js, CSS, and backend. 

But still, we didn't cover all the technologies that are important for front-end developers; that's why today, I decided to create a list of 14 questions about Angular, which can be very helpful in your next interview for the position with Angular.

I'm going to start with the fundamental information that can be useful for junior developers, and then I'll also cover some more advanced aspects of this framework.

Of course, you must remember about preparing from other programming aspects like Javascript, HTML, and CSS. But I hope you'll find this list of questions and answers useful before the next interview.

As always, I have a video for those who prefer watching and listening to the explanation rather than just reading.

{% youtube x8788fGNVfk %}

Let's start!

### 1. What’s the difference between AngularJS and Angular?

|                      | AngularJS                       | Angular                                        |
|----------------------|---------------------------------|------------------------------------------------|
| Language             | Javascript                      | Typescript                                     |
| Mobile Support       | doesn’t support mobile browsers | supported by all popular mobile browsers       |
| Dependency Injection | no Dependency Injection used    | hierarchical Dependency Injection system use |
| Routing              | $routerprovier.when() for router configuration                      | @Route Config{()} for configuration                                     |
| Structure            | less manageable comparing the Angular | easier to create and maintain large application       |
| Architecture         | supports MVC design             | uses components and directives, components are the directives with template |
| Binding Events       | specific ng directives for events    | using () and [] to bind events and properties binding |

### 2. Describe components, modules, and services in Angular?

A. **Components** are the most basic building blocks of the Angular framework. They consist of three parts: view, class, and styles. View element loads and renders the template, styles element takes care about loading the styles, and class part are responsible for the logic of the component. Components can be created using Angular CLI command: `ng generate component <name>`. Here’s the example of the empty component:

```
import { Component, OnInit} from '@angular/core';

@Component({
  selector: 'app-component',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {

  constructor() { }
  ngOnInit() {
  }
}
```
	
B. **Modules** refer to places where we can group components, directives, and services in an Angular app. There can be two types of modules: root and feature. Each application can have one root module and many feature modules. To define a module, we have to use `NgModule` decorator, and each application has one module created with the application at the beginning. Here’s the code example of the `app.module.ts`.

```
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }
```
	

C. **Services** are the classes whose main objective is to share data and functions among different Angular app components. Services are created using `@Injectable` decorator, and functions from services can be invoked from any components or directives. Here’s the example of an empty service.

```
import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class AppService {

  constructor() { }
}
```

### 3. What are directives in Angular?

**Directive** is a very important concept in Angular. It’s used to extend the HTML and giving it a new syntax. Directives can be predefined or custom.

Types of directives:
**component directives** - every component in Angular is actually a directive with a template.
**attribute directive** - this kind of directive can manipulate the DOM by changing the behavior and styles. This directive is used, for example, for the conditional styling of the elements.
**structural directive** - it’s used to create and destroy the elements of the DOM, the example of this kind of directive is `*ngIf` or `*ngFor`. 

### 4. How does Dependency Injection work in Angular?

Dependency Injection (DI) is a very important concept in Angular2+. With Dependency Injection classes can receive dependencies from other classes or services. 

For example, dependency injection in Angular application can be visible when defining a function in the service and calling that function in the component. 

To make a service or class injectable, we need to use `@Injectable` decorator. 

Let’s take a look at the image when I tried to illustrate the dependency injection in Angular application.

![Dependency Injection in Angular](https://dev-to-uploads.s3.amazonaws.com/i/mt44q4mbfk3d7jco4gqg.png)

In the image above, you can see the Injectors, which are UserService and OrderService. Then UserService in injected the component below, passing it to the constructor. Then it’s possible to use methods from UserService inside the component.

### 5. What’s the difference between Angular expressions and Javascript expressions?

- Angular expressions are evaluated in the scope context; Javascript expressions are evaluated in the global context;
- Expression evaluation in Angular returns `undefined` or `null`, in Javascript it returns `ReferenceError` or `TypeError`;
- In Angular expressions commas and void are not allowed;
- In Angular expressions we shouldn’t define functions;

### 6. Describe data binding in Angular?

Data binding is a concept of communication between the component and the DOM object. In Angular, we can use one-way data binding and two-way data binding. 

The one-way data binding (unidirectional) allows us to bind data only from component to the view or from the view to the component. In Angular, it can be handled in a few ways.

**Interpolation: `{{data}}`** - it passes the data from the component to the template.
```
<p>Hello. My name is {{name}}.</p>
```

**Property binding: [property]= "data"** - it passes a value from the component to the specific property of the HTML element, such as the value to the input element. It can be used for classes and styles as well.
```
<input type="text" [value]="Hello World">
```

**Event binding: (event)= "function"** - it passes data from the DOM object to the component. If any event happened, the component gets the information and can perform an action.
```
<button (click)="submit">Send</button>
```

Those methods are one-way data binding, but as I mentioned before, it's also possible to use two-way data binding in Angular and pass data in both ways. For that, we use the ngModel (Angular's directive for binding value of HTML elements to the application) and [()] syntax. It's a great idea to use it, for example, in the inputs.

**Two-way data binding: [(ngModel)]="data"**

```
<input [(ngModel)]="productName">
```

In our example, the value used for the input is `productName`, but if the user will change it, the value in the input will change as well.

### 7. What’s AOT and JIT, and what’s the difference?

Angular application has to be compiled before the browser can understand it and run. There are two methods of compilation provided by Angular framework: 

- Ahead of time (AOT)
- Just in time (JIT) 

The JIT compilation happened during browser runtime, and the AOT compilation happens during the build process. Let’s take a look at the graphic below.

![JIT vs AOT](https://dev-to-uploads.s3.amazonaws.com/i/7f7e6q9rslfisv2hnjae.png)

In the image above, you can see the stages that the application is going through before seeing it on the screen. 

The main advantage of AOT is the faster rendering of the application because the code is ready to be shown when the browser downloads it. It also minimizes errors because they are detected and handled during the building phase. It also provides better security.

By default, Angular apps are compiled with the JIT method. To compile with AOT, it’s enough to use `—aot` flag after `ng build` or `ng serve`.

### 8. How Angular Router works?

Angular Router is an official routing library build be the Angular Core Team.
The most important functionalities of the Angular Router are:

 - allowing to navigate from one view to another without reloading;
 - updating the history of the browser, so the user can navigate with the browser back and forward functionality;
 - activating the components that are required to display a particular view connected with the path;
 - allowing to redirect;
 - allowing to lazy load some parts of the app;
 - activating or deactivating a particular URL, according to the guards.

Let’s take a look at the image and let’s got through the steps that the Router does to display the page.

![Angular Router](https://dev-to-uploads.s3.amazonaws.com/i/9m1nognbd1faykxa004h.png)

In the image above, you can see the six steps that Angular Router does from taking the URL from the browser to display the component. 

### 9. Explain Lifecycle Hooks

Every component in Angular has its lifecycle and different stages of the lifecycles. Each lifecycle has hooks that allow us to interact with the component on the specific phases.

Let’s take a look at the hooks of Angular components.

**ngOnChanges()** - it’s the method that is called once when the component is created, and later every time, any input properties of the component will change. It takes a SimpleChanges object as a parameter. It gives and the current and previous value of the input if that exists.

**ngOnInit()** - it’s the most popular hook in the Angular component lifecycle, and it’s invoked once per component lifecycle, just after the first `ngOnChanges()` method. It’s the place where we can do server requests or any other initialization logic. 

**ngDoCheck()** - it’s used to detect changes that are not detected by Angular itself. It’s called on every change detection, after two first methods. This hook is not good for performance as it’s invoked very frequently, so it should be used carefully. 

**ngAfterContentInit()** - this method is called only once, after first ngDoCheck() and it gives us access to ElementRef of the ContentChild.

**ngAfterContentChecked()** - this hook get called after ngAfterContentInit() and after every ngDoCheck(). 

**ngAfterViewInit()** - this lifecycle method is called after the component’s view or child component’s view is initialized. It’s called once after the first ngAfterContentChecked() method.

**ngAfterViewChecked()** - this hook responds when Angular checks the component’s view and component’s child views. It’s called after ngAfterViewInit() and after every ngAfterContentCheck().

**ngOnDestroy()** - it’s the last method of the Angular’s component lifecycle. It’s the place where we should clean up our component before destroying it, which means we should unsubscribe observables or events. It’s called just before Angular destroys the component.


## 10. What’s Rxjs (Reactive Extensions for Javascript)?

Rxjs is a library, commonly used with Angular framework. It supports reactive programming, which is the asynchronous programming paradigm focused on data streams and change propagation.

Rxjs use Observables, which make it easier to create asynchronous code; it also provides some utility function to help us use work with Observables. 

### 11. What’s the difference between observables and promises?

| Promise                         | Observable                                     |
|---------------------------------|------------------------------------------------|
| Emits one event                 | Emits multiple events                          |
| Not lazy                        | Lazy, needs subscriber                         |
| Cannot be canceled              | Can be canceled with .unsubscribe() method     |
| Always asynchronous             | Can be synchronous and asynchronous            |
| Nothing like that for Promise   | Have many operators that can be used with Observable (like map, filter)       |

### 12. What’s the Subject, and what are the Subject types?
	
Subject is similar to Observable, it can be subscribed and unsubscribed. It also have the same set of methods like .next(), .error(), .complete().

The Subject is multicast, and Observable is unicast.

With observables, each subscriber can get different values, and with Subject, one observable execution is shared among many subscribers. Also, Subject can be used as data subscribers and data consumers, but Observable can’t be data consumers. 

There are three types of subjects:

**Behavior Subject** - they store the current value, and because of that, we can always directly get the last emitted value from the Behavior Subject. It can be done using .value property or by subscribing to the Subject. 

 The Behavior Subject can be created with the initial value, which isn’t very easy with Observables.

**Replay Subject** - this kind of Subject is similar to the Behavior Subject in case of passing current value to the new subscribers. 

But Reply Subject goes even further. It gives us the possibility to define how many values we want to „remember” and for how long. Then the amount of values is sent to the new subscriber. 

**Async Subject** - in this case, only the last value of the Observable execution is sent to the subscriber, and it’s sent only when the execution completes, so the .complete() method needs to be called.

### 13. How components interact with each other in Angular?

Passing data between Angular components can be done in a few different ways, depending on the relation between the components.

In the case of Parent to Child relationship, we can use @Input decorator. Let’s take a look at the code example.

```
// Parent component
import { Component} from '@angular/core';

@Component({
  selector: 'parent-component',
  templateUrl: `<child-component [userName]=userName></child-component>`,
  styleUrls: ['./parent.component.scss']
})
export class ParentComponent {
  userName:string = "Judith";
  constructor() { }
}

// Child component
import { Component, Input} from '@angular/core';

@Component({
  selector: 'child-component',
  templateUrl: `<div>{{userName}}</div>`,
  styleUrls: ['./child.component.scss']
})
export class ChildComponent {
  @Input() userName:string;
  constructor() { }
}
```

In the code example above, you can see the parent component that has a `userName` property, and it passes it to the child component. In the child component, we use `@Input` decorator to receive the data and display it.

From Child to Parent, we can use @ViewChild decorator. Let’s also take a look at the code example.

```
// Parent component
import { Component, AfterViewInit, ViewChild } from '@angular/core';
import { ChildComponent } from './child.component.ts';

@Component({
  selector: 'parent-component',
  templateUrl: `<div>{{userName}}</div>`,
  styleUrls: ['./parent.component.scss']
})
export class ParentComponent implements AfterViewInit {
  userName:string;
  @ViewChild(ChildComponent) child;
  constructor() { }

  ngAfterViewInit() {
    this.userName = this.child.userName;
  }
}

// Child component
import { Component } from '@angular/core';

@Component({
  selector: 'child-component',
  templateUrl: `<div>{{userName}}</div>`,
  styleUrls: ['./child.component.scss']
})
export class ChildComponent {
  userName:string = 'Judith';
  constructor() { }
}
```

In the code example above, I used @ViewChild in the parent component, which allowed me to access data from the child component in the parent component.

Another example of passing data from child to parent component is with @Output and EventEmitter.

```
// Parent component
import { Component } from '@angular/core';

@Component({
  selector: 'parent-component',
  templateUrl: `<child-component (data)="getData($event)">`,
  styleUrls: ['./parent.component.scss']
})
export class ParentComponent {
  constructor() { }
  getData($event) {
    this.data = $event;
  }

}

// Child component
import { Component, Output, EventEmitter } from '@angular/core';

@Component({
  selector: 'child-component',
  templateUrl: `<button (click)="getData()">Click</button>`,
  styleUrls: ['./child.component.scss']
})
export class ChildComponent {
  userName:string = 'Judith';
  @Output() getData = new EventEmitter<string>();

  constructor() { }

  getData() {
    this.getData.emit(this.userName);
  }
}
```

In this example, we used @Output and EventEmitter for passing the data from the child component to the parent component.

We can also pass data through the services if the components are not connected with each other directly. 

### 14. What are Angular pipes?

Pipes in Angular are classes with @Pipe decoration, which transform data input to required data output according to the logic in the pipe.

### Conclusion

In this article, I went through the most popular questions asked during the interview for front-end developers with Angular. 

I’ll start by covering basic information like the difference between AngularJS and Angular or which are models and directives. Also, I covered some more advanced concepts like Observables and Subjects.

I hope you’ll find this article useful, but keep in mind that preparation from different technologies is necessary as well. Please take a look at the list of the Javascript interview questions we’ve prepared.

[Javascript interview questions](https://www.blog.duomly.com/tags/interview-questions/)

<a href="https://www.duomly.com?code=lifetime-80">![Duomly promo code](https://dev-to-uploads.s3.amazonaws.com/i/g1627qcm3gc9m3bsfzfy.png)</a>

Thank you for reading and good luck on your next interview, 
Anna