In this blog, I have prepared a set of important Angular interview questions and their answers which are very important from the point of the interview.
The Angular interview questions given below are based on versions 8 and 9 of Angular.
Angular is outstanding amongst other programming languages in 2020. Created and maintained by Google, it assists software engineers with building adaptable and performant web applications.
This collection of Angular interview questions will surely be useful for your job interview, however before we get into that, let us rapidly recap about Angular.
1. What is Angular?
Angular is a well-known powerful web application framework which helps to develop single-page applications. It is a Type Script-based open-source technology used to develop performance-oriented web applications. To provide a better stability and highly optimized web application, Angular has released multiple versions from time to time.
For more about Angular introduction, please visit this link – Angular Introduction
Below are the versions of Angular
Version | Release Date | LTS (Long term support) |
---|---|---|
11 | Nov, 2020 | Yes |
10 | Jun, 2020 | Yes |
9 | Feb, 2020 | Yes |
8 | May, 2019 | Yes |
7 | Oct, 2018 | No |
6 | May, 2018 | No |
5 | Nov, 2017 | No |
4 | Mar, 2017 | No |
2. What is TypeScript?
TypeScript is a typed superset of JavaScript that compiles the code into JavaScipt. To work with TypeScript, first, you have to install the node package manager from npmjs.com Once npm installation is done, open the command prompt and type the below command.
npm install -g typescript – This command will install TypeScript globally to your system.
To check the version, use this command tsc --version
– This will show you the installed version of TypeScript. Learn TypeScript
3. Explain the Lifecycle Hook in Angular
- ngOnChanges
- ngOnInit
- ngDoCheck
- ngAfterContentInit
- ngAfterContentChecked
- ngAfterViewInit
- ngAfterViewChecked
- ngOnDestroy
4. Angular CLI Commands
Below are a few Angular CLI commands that are useful while developing an Angular Application. To install Angular CLI
npm install -g @angular/cli
Get online help:
ng help
Command to get detailed help from a command
ng [command name] --help
To get Angular version details
ng --version
For more list of Angular CLI commands, please visit this link – Angular CLI Commands
5. What are the Components of an Angular Project?
Component is the basic building block of an Angular application. Any web page you see in Angular is a component. Any Angular project is a collection of multiple components. A component is a part of a module within an Angular project.
A component is mainly a collection of 4 files – .html, .ts, .scss, .spec.ts A single component is responsible for handling a single view.
An angular project must have at least one component. When creating a new project we have a component file named app.component
(app.component.ts
and app.component.html
)
To add a new component within your Angular project, run the below command – ng g c
Whenever we create a new component, it is defined in its respective module file.
6. What is a Module?
The basis of any angular project is a Module. Simply, the Module is a collection of components. By default, in every Angular project, there is a Module file called root module (app.module.ts)
Multiple modules can be created within a single Angular application. Suppose that you are working on a project that is very big and complex.
In such a project or application, you will need more than one Module file, so that your application will be simple and well-maintainable.
For eg – You can create a module for Customer, another module for Admin and so on. You can create components for your customer within the Customer module and components for the admin section within the Admin module. To add a new module within your project, run the below command – ng g m
7. What is a Directive in Angular?
It is another important interview question. Directives in Angular extend the use of HTML elements by adding custom behaviour. In this blog, we will see the use of directives in Angular. There are 3 types of directives in Angular –
- Component Directives: Components are the most common directives among all. We can not create an Angular app without component directives. The naming convention of a component in the Angular app is .component.ts
- Structural Directives: Structural Directives make changes in DOM by altering DOM elements. Structural directives in Angular start with *
- Attribute Directives: Attribute directives make changes in the appearance and behaviour of an element or component.
Visit this link to know more about Directives in Angular – Directives in Angular
8. Explain ngIf, ngSwicth, ngFor directives
ngIf
, ngSwicth
, ngFor
is a structural type of directive as these directives make changes in DOM by modifying the DOM elements. Click Here to learn more about Angular Directives.
9. What is Interpolation in Angular?
Interpolation is a way to bind a value in a component’s template. For eg – {{Property_Name}} In Component.ts file
export class TestComponent implements OnInit { message: any; constructor( ) { } ngOnInit() { this.message = 'Hello to Angular' }
In the template file –
{{message}}
10. What is Event Binding in Angular?
Event binding enables the template file to listen for keypress, mouseclick, touches etc.
<button (click)="ShowAlert()">Show</button> Or you can use like this- <button on-click="ShowAlert()">Show</button>
11. What are Pipes? Use of Pipes in Angular with examples.
Pipes in Angular transform the data before it displays it for viewing. Angular offers built-in pipes and custom pipes as well. To apply a pipe Angular uses the | symbol before any pipe. Syntax to use pipe in Angular – {{| }} Few built-in pipes are – lowercase, uppercase, date etc.
12. How to create Custom Pipes?
If your requirement is fulfilled with built-in pipes then use them else you may create custom pipes to fulfil business requirements. First, we have to generate files to work with a custom pipe. To do this use the below command ng g p Create a pipe with name add which will do addition for a given value and parameter. To generate a custom pipe with name add, we will use the below command.
ng g p add
Once we have generated the custom pipe files, we will modify the code as per our requirements. Open add.pipe.ts
file in the editor and make changes in transform()
method.
export class AddPipe implements PipeTransform { transform(value: number, args: any): any { if(args) { return value + args; } else return value; } }
Import this pipe in the respective module –
import { AddPipe } from './pipe/add.pipe';
Add this pipe in the declaration as well as in the module file. Now use the below line in your component and run the project to see the outpout.
{{10 | add:5}}
13. Explain Routing in Angular
Routing means navigating from one page to another page in an application. While creating a new Angular project through CLI, it asks ‘Would you like to add Angular routing? (y/N)’ Once you select yes, it creates a app-routing.module.ts
file in the src-> app folder. We have to define all the routes in Routes in the routing module file. Routes are an array of route configurations.
const routes: Routes = [ { path: 'demo1', component: Demo1Component }, { path: 'add-product', component: AddProductsComponent }, ];
For more details on Angular Routing, please visit our blog – Routing in Angular
14. What is Route Guard in Angular?
Route guards in an Angular application facilitate to block of a particular route based on user authentication or on some extra permissions. Use the below command to create a route guard –
ng g g /guard/userguard
Import the newly created route guard in your module file. and add the routeguard name in the provider’s array in the module file. Now, define the route with the route guard in app-routing.module.ts
the file
{path:'dashboard',component:DashboardComponent,canActivate:[UserguardGuard]}
The above route says DashboardComponent
can only be displayed if canActivate
the method of Userguard returns true. In routeguard
file, check the condition, if it matches the specified condition then return true else navigate to the access denied page and return false. For more details on route guard, please visit this link – Route Guard in Angular
15. What are the differences between Template Driven Form and Reactive Form approach?
It is one of the important Angular interview questions.
In the template-driven approach, Forms input and Forms validation logic go into the component’s HTML file only. The template-driven approach is fine for small or medium-level projects.
In the Reactive Form approach, the validation function is written in the component class. Angular calls this function whenever there is a change of value in the input control. The reactive Form Approach is the best practice if we are working on a large and complex Angular application. For more details about Template Driven Form and Reactive Form approach, please visit this link – Template-driven and Reactive Forms approach
16. What is FormControl and FormGroup?
- FormControl: All input fields defined in the HTML template are the instance of FormControl.
- FormGroup: It is an instance of a set of form controls referred as FormGroup
For more details about FormControl and FormGroup, please visit this link – FormControl, FormGroup and FormBuilder
17. What is FormBuilder Service in Angular
FormBuilder service uses group()
method which takes an object with a control name as the key. To use FormBuilder in an Angular project, first import FormBuilder from angular/forms as shown in the code snippet below.
import { FormBuilder } from '@angular/forms';
addProductForm = this.formBuildr.group( { productName: [], productCategory: [], productDetails: [], productCost: [] } );
For more details about FormBuilder
Service, please visit this link – FormControl, FormGroup and FormBuilder
18. What is FormArray in Angular?
FormArray is the collection of FormControl, FormGroup or FormArray. To use FormArray in an Angular application, you have to import it like this –
import { FormGroup, FormBuilder, FormArray } from '@angular/forms';
productForm: FormGroup; products: FormArray;
addProductItem(): void { this.products = this.productForm.get('products') as FormArray; }
<div formArrayName="items" *ngFor="let p of productForm.get('products').controls; let i = index;"> <div [formGroupName]="i"> <input formControlName="pname" placeholder="Product name"> <input formControlName="details" placeholder="Product details"> <input formControlName="cost" placeholder="Cost"> </div> </div>
19. What is HttpClient?
HttpClient is available in '@angular/common/http'
and it offers a way to communicate with an API. And it uses XMLHttpRequest which supports all the latest browsers to communicate with an endpoint. It also uses RxJS observables which allows the Angular app to handle asynchronous operations.
For more details about HTTP Client, please read the below blogs –
20. What is Observable in Angular?
It is one of the most asked Angular interview questions.
Observable is available with the RxJS library. Angular uses Observable to implement the asynchronous process. Observable gets executed when a consumer calls a Subscribe()
function.
For details about Observable, please check this blog – Angular CRUD example with .Net Web API
21. What is JIT Compilation?
JIT stands for Just-in-time compilation and it is the default compilation mode used by Angular. This compilation converts the HTML and TypeScript code into JavaScript code at runtime.
JIT Compilation command –
ng build ng serve
22. What is AOT Compilation?
AOT stands for Ahead-of-Time, AOT compilation converts HTML and Type script code into JavaScript code at build time. This is the recommended compilation mode for production.
AOT compilation commands –
ng build --aot ng server --aot
23. Explain One-Way Binding and Two-Way Binding in Angular
What is One-Way Binding in Angular?
One-way data binding will bind data from the component to the view (DOM) or from the view to the component.
It is unidirectional. You can just bind the data from the component to the view or vice-versa.
There are various ways of data binding which utilize one-way data binding from component to view.
The following are the ways, which use one-way data binding in Angular.
- Interpolation Binding
- Attribute Binding
- Property Binding
- Style Binding
- Class Binding
What is Two-Way Binding in Angular?
Two-way data binding in Angular will assist users exchange data from component to view and from view the component. It works in a bi-directional manner.
Two-way data binding can be accomplished with ngModel
directive in Angular.
The below angular code shows the data binding (ngModel), which is fundamentally the mix of both the square brackets of property binding and parentheses of the event binding.
<input type=”text” [(ngModel)] = ‘value’ />
24. What are Decorators in Angular?
Decorators are utilized to attach metadata to program components, for example, classes and properties. Metadata is utilized to determine insights regarding program entities. Decorators give special importance to program elements. Here we will take a gander at probably the most generally utilized Decorators in Angular 2 and above.
There are mainly 4 types of decorators available in Angular.
- Class Decorators – Example @Component and @NgModule
- Property Decorators – It is used for properties inside a class. Example – @Input and @Output
- Method Decorators- It is used for methods inside a class. Example – e.g. @HostListener
- Parameter Decorators – It is used for parameters inside the constructor of a class. Example – @Inject
25. What are Class Decorators in Angular?
Angular offers us multiple class decorators. Every decorator has its role. They are the high-level decorators that we use to express the goal for classes.
To make an Angular class as a component, we need to decorate the class with the @Component decorator.
In basic words, a class decorator tells the nature of that class implies this class is a module or component.
Simply add the decorators to the class and Angular will do the rest of the things.
Refer to the code snippet for a better understanding:
@Component({ selector: 'app-demo-component', templateUrl: 'demo-component.component.html', styleUrls: ['deom-component.component.scss'] }) export class ExampleComponent { constructor() { //This class is Component. Write your class code here } } @NgModule({ imports: [], declarations: [], }) export class ExampleModule { constructor() { //This class is a module. Write your class code here. } }
26. Explain the differences between Decorators and Annotations
Below are the differences between Decorators and Annotations –
Decorators –
- It is used to attach metadata to a class in Angular.
- It is used by the TypeScript compiler.
- By default, Decorators are supported in Angular.
Annotations –
- It reflects the library of metadata.
- It is a hard-coded feature.
- It is used by the Traceur compiler.
27. Explain the differences between Promise and Observables
The below table depicts the differences between Promise and Observables in Angular.
Promise | Observables |
---|---|
It emits a single value at a time. | Observables can emit more than one value at a single time. |
Promise can not be cancelled. | It can be cancelled using unsubscribe() method. |
It doesn’t have any operations. | It provides a map for the filter , forEach |
It throws an error to the child’s promises. | It throws the error to the subscribers. |
28. How to pass data from the Parent component to the Child component in Angular?
If the parent component wants to send data to the child component then we have to use @Input
decorator in case the child component wants to send data to the parent component then we use @Output
decorator.
A demonstration with a code snippet is available below link –
How to pass data from one component to another component in Angular?
29. What do you mean by Dirty Check in Angular Form?
To stop the validator from showing errors before the user gets an opportunity to modify the form data, you should check for either the dirty or touched states in a control.
At the point when the user changes the value in the watched field, the control is set as “dirty”.
At the point when the user focuses on the form control, the control is set as “touched”.
It checks whether a value has changed that hasn’t yet been synchronized across the application.
this.myForm.markAsDirty(); this.myForm.markAllAsTouched();
30. Name some of the events in Angular.
- (click)
- (submit)
- (blur)
- (focus)
- (keyup)
- (keypress)
- (keydown)
- (mousedown)
- (mouseenter)
31. How to consume an API using HttpClient in Angular?
HttpClient in Angular is used to consume a service to perform CRUD (Create, Read, Update and Delete) operation.
HttpClient is available in '@angular/common/http'
and it offers a way to communicate with an API. HttpClient uses XMLHttpRequest which supports all the latest browsers to communicate with an endpoint.
HttpClient uses RxJS observables which allows the Angular app to handle asynchronous operations.
A demonstration with a code snippet is available below link –
How to consume API from Angular?
32. What’s new in Angular 11?
- TypeScript 4.0 support
- Webpack 5 Support
- Faster Build
- Moving from TSLint to ESLint
33. What is an Async pipe?
The Async pipe in Angular is used to subscribe to an observable or promise to return the latest value.
You can use an Async pipe like this –
<tr *ngFor="let prd of ProductList | async">Read this – Angular CRUD example with .Net Web API
Hope these Angular interview questions and answers are helpful to you.
Please share this within your community and comment below in case you have any feedback.
Conclusion
This article contains 30 interview questions and answers to Angular. This is a good amount of questions which you should read once.