Angular Interview Questions

I am sharing top 50 Angular Interview Questions, which will help you to crack the Angular test and Interview.

Q1:- What is Angular?

Ans:- Angular is a single page client application and using HTML and Typescript.

Q2:- Advantages of Angular 2 over Angular 1?

Ans:- Angular 2 is written entirely in Typescript and meets the ECMAScript 6 specification. Angular 2 is entirely component-based. Controllers and $scope are no longer used. They have been replaced by components and directives.

Q3:- What is a component?

Ans:- Components are basically classes that interact with the .html file of the component, which gets displayed on the browser. app component is a parent component while we create a component through command


     ng g c componentName
     

Q4:- what is Decorator?

Ans:- Decorator is a design pattern in the Angular. It has a core concept and used to develop a project in the Angular. every decorator starts with @. there are mainly 4 types of decorators.

1) Class Decorator
2) Property Decorator
3) Method Decorator
4) Parameter Decorator

readmore…

Q5:- What is the command to create a component via cli?

Ans:- ng g c “componentName”

Q6:- How to install a bootstrap module?

Ans:- npm install bootstrap –save
and include file path in the angular.json file in the style section.

Q7:- How many types of Binding are there in Angular?

Ans:- Basically, there are two types of Binding in Angular.
1) One Way Data Binding:- It is used to data transfer from component to view or view to the component.
2) Two Way Data Binding:- Two-way data binding is used, when you want to exchange data from the component to view and from view to the component.

to get the complete information click on readmore…

Q8:- What is the syntax of *ngFor?

Ans:-


	<li *ngFor="let item of items; let i = index">
        {{i}} {{item}}
        </li>
  

Q9:- Difference between for in and for of?

Ans:- for in:- This is used to get the key and value from object.

Suppose, you have employee object


	let employee = {
	   "first_name": "John",
	   "last_name": "Mathew",
	   "age": 35
	}
	

Now, you want to get employee details from the employee object.


    for(const key in employee) {
    console.log( employee[key]);
   }
   
Output:-
John
Mathew
35

for of:- this is used get the value from the array.
Suppose, you have fruits array


   let fruits=['Apple','Banana', 'Orange', 'Mango'];
   

Now, get the fruits Name.


   for(let fruit of fruits){
    console.log(fruit);
   }
   
Output:-
Apple
Banana
Orange
Mango

Q:10:- How can we talk from a template to its component?

Ans:- Through Event Binding

Q11:- How do we encapsulate Component Styles in Angular?

Ans:- we can add css file in the @component decorator or add css code into this like


     styles: ['h1 { font-weight: normal; }']
     

Q12:- Difference between css and scss?

Ans:- SCSS:- Syntactically Awesome Stylesheet is the superset of CSS.SCSS contains all the features of CSS and contains more features that are not present in CSS which makes it a good choice for developers to use it. SCSS offers variables, you can shorten your code by using variables. It is a great advantage over conventional CSS.

Example:-


$white: #ffffff;
$ubuntu-font: $ubuntu-font: 'Ubuntu', 'Arial', 'Helvetica', sans-serif;
body{
 color: $white;
 font: $ubuntu-font;
 padding: 2rem;
}

Q13:- Explain Angular Lifecycle?

Ans:- Angular call life cycle hook method when you create/modified/destroy component and directive.
there are eight angular hook methods.
1) ngOnChanges()
2) ngOnInit()
3) ngDoCheck()
4) ngAfterContentInit()
5) ngAfterContentChecked()
6) ngAfterViewInit()
7) ngAfterViewChecked()
8) ngOnDestroy()

to read the complete details click on the readmore..

Q14:- what is a pipe and how to create a custom pipe?

Ans:- Pipe:- A pipe takes data as an input and transforms it into the desired output.
in the component html file


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

To create the pipe:- @Pipe decorator used with


import { Pipe, PipeTransform } from '@angular/core';

Q15:- How to pass data from a parent component to its children and vice versa?

Ans:- @Input():- this decorator is used to data transfer from parent component to child component.
@Output():- this decorator is used to data transfer from child component to parent component with the help of EventEmitter.

to get the more details in @Input() decorator click on the readmore..
to get the more details in @Output() decorator click on the readmore..

Q16:- How to create a service in Angular?

Ans:- ng g s serviceName

Q17:- How can we maintain Singleton Pattern in a Service?

Ans:- A singleton service is a service instance that is shared across components. There are two ways to make a service a singleton in Angular: Declare root for the value of the @Injectable() providedIn property. Include the service in the AppModule or in a module that is only imported by the AppModule.
First way:-


@Injectable({
  providedIn: 'root'
})

SecondWay:-
In NgModule


@NgModule({
  ...
  providers: [UserService],
  ...
})

Q18:- What is Dependency Injection in Angular?

Ans:- Dependency injection (DI) is a design pattern where objects are passed to another object to complete the tasks. In angular, service or component may require other dependent services to complete a task.
Example:- create a service and integrate it into the component.

Q19:- Difference between an observable and a promise?

Ans:- Observable:- 1) Observable emits multiple values over a time.
2) You may cancel an Observable with the unsubscribe() method
3) Observable provides a lot of efficient operators like map, foreach, filter, reduce, retry, etc.

Promise:- 1) A Promise emits a single event at the completion or failure of an async operation.
2) Promise emits a single value
3) A Promise is not lazy and promise cannot be canceled.

Q20:- What is First Operator?

Ans:- It is the operator of the RxJS library. it is used to get the first element value from the array.

Q21:- What is Take operator?

Ans:- It is the operator of the RxJS library. it is used to get the element value from the array.


        import { take } from 'rxjs/operators';
		const source = of('Mango', 'Orange', 'Banana', 'Apple', 'Pine-apple');
		//take the first emitted value then complete
		const example = source.pipe(take(1));
        
Output:- Mango

Q22:- Difference between Hot Observable and cold Observable?

Ans:- Hot Observable:- Observable is hot when the data is produced outside the Observable.


import * as Rx from "rxjs";

const random = Math.random()

const observable = Rx.Observable.create((observer) => {
    observer.next(random);
});

// subscription 1
observable.subscribe((data) => {
  console.log(data); // 0.11208711666917925 (random number)
});

// subscription 2
observable.subscribe((data) => {
   console.log(data); // 0.11208711666917925 (random number)
});

Cold Observable:- An Observable is cold when data is produced inside the Observable.


import * as Rx from "rxjs";
const observable = Rx.Observable.create((observer) => {
    observer.next(Math.random());
});

// subscription 1
observable.subscribe((data) => {
  console.log(data); // 0.24957144215097515 (random number)
});

// subscription 2
observable.subscribe((data) => {
   console.log(data); // 0.004617340049055896 (random number)
});

Q:23- What is subject in Rxjs?

Ans:- A Subject is like an Observable. The main reason to use Subjects is to multicast. An Observable by default is unicast.

Q24:- What is Behaviour Subject?

Ans:- The BehaviorSubject has the characteristic that it stores the “current” value. This means that you can always directly get the last emitted value from the BehaviorSubject.

example:- an event stream of birthdays is a Subject, but the stream of a person’s age would be a BehaviorSubject.

Q24:- What is change Detection?

Ans:- Change Detection means updating the DOM whenever data is changed. whenever any data is changed, Angular will run the change detector to update the DOM.
there are 3 methods
1) onPush Change Detection
2) Behaviour Subject
3) ChangeDetectorRef

Q25:- What do you mean by ViewEncapsulation?

Ans:- View encapsulation defines whether the template and styles defined within the component can affect the whole application or vice versa.
there are 3 types of View encapsulation

1) ViewEncapsulation.None:- in ViewEncapsulation.None, the style gets moved to the DOM’s head section and is not scoped to the component. There is no Shadow DOM for the component and the component style can affect all nodes in the DOM.


import { Component, ViewEncapsulation } from '@angular/core';
@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css'],
    encapsulation: ViewEncapsulation.None
})
export class AppComponent {
    title = 'parent component';
}

2) ViewEncapsulation.Native:-
1) Angular will create Shadow DOM for the component.
2) Style is scoped to the component.

in body tag:-
#shadow-root

3) ViewEncapsulation.Emulated:-

1) Angular will not create a Shadow DOM for the component.
2) The style will be scoped to the component.
3) This is the default value for encapsulation.

Q26:- What is a router outlet?

Ans:- router outlet:- You can create a named Router outlet using the name property of the router-outlet


<router-outlet  name="outlet1"></router-outlet>

Q27:- What is the interceptors?

Ans:- Interceptors are a way to do some work for every single HTTP request or response.

example:- Add a token or some custom HTTP header for all outgoing HTTP requests.

Q28:- What is the router resolve?

Ans:- The Angular 8 Router provides a resolve property that takes a route resolver and allows your application to fetch data before navigating to the route
You can create a route resolver by implementing the Resolve interface.


import { Injectable } from '@angular/core';
import { APIService } from './api.service';
import { Resolve } from '@angular/router';

@Injectable()
export class APIResolver implements Resolve {
  constructor(private apiService: APIService) {}
   resolve() {
    return this.apiService.getItems();
  }}

Q29:- What is CORS?

Ans:- Cross-origin resource sharing (CORS) is a mechanism that allows restricted resources (e.g. fonts) on a web page to be requested from another domain outside.

Q30:- Types Of Request Method?

Ans:- get,post,put,delete,patch

Q31:- How do we include JS and css file in Angular?

Ans:- we can add js and CSS files in the angular.json file which is included in the scripts and styles array.

Q32:- How to apply a loader in one place and used in the entire project?

Ans:- Through Interceptor we can define add in every request.

Q33:- what is the use of angular.json file?

Ans:- It has project name, root directory as source folder (src) name which contains all the components, services, directives, pipes, the starting point of our application (index.html file), the starting point of typescript file (main.ts), style files (style.css).

Q34:- why use ng build –prod?

Ans:- ng build –prod compiles with Ahead of time compilation.
Ahead of time compilation(–aot):- The AOT compiler detects and reports template binding errors during the build step before users can see them.

Q35:- What is ForRoot and forChild in the router?

Ans:- RouterModule.forRoot() is used to handle the routing in the AppModule. It is the one that instantiates the router services. All other modules will use the RouterModule.forChild([]) for handling the routing.

Q36:- what is Angular Directive?

Ans:- Angular Directive is basically a class and declares with @Directive decorator. Directives are used to add behavior to an existing DOM element.

The Angular Directive can be classified into three types:
1) Component Directive
2) Structural Directive
3) Attribute Directive

to get the complete details of Angular Directive, click on the readmore…

Q37:- What are webSocket?

Ans:- WebSocket is the internet protocol that allows for full-duplex communication between a server and clients. the server may send data to a client without the client initiating a request. WebSockets is used for chat apps etc.

Q38:- Types of Form in Angular?

Ans:- here are two type of forms in angular
1) Template Driven Form
2) Model driven forms (Reactive Forms)

to get the complete details of Angular form, click on the readmore…

Q39:- What is the dynamic component?

Ans:- Dynamic components located in the application are not defined at build time. That means that it is not used in any angular template. Instead, the component is instantiated and placed in the application at runtime.
like angular material dropbox.

Q40:- what is rxjs?

Ans:- Reactive Extensions for JavaScript (RxJS) is a reactive streams library that allows you to work with asynchronous data streams. RxJS can be used both in the browser or on the server-side using Node.

Q41:- What is platform-browser in angular?

Ans:- @angular/platform-browser Supports execution of Angular apps on different supported browsers.

Q42:- What is PWA (Progressibe web App) in angular?

Ans:- your app can work without an internet connection.

Q43:- what is angular material?

Ans:- Angular Material 7 is a UI component library for Angular developers. Angular Material components help in constructing attractive, consistent, and functional web pages and web applications.

Q44:- What is a module in Angular?

Ans:- Angular Module is a group of components, directives, services that are related. An angular module can include another module.
the default angular module is an App module when you setup a project in angular. you can create a custom module through command.
to get the complete details, click on the readmore…

Q45:- What is lazy loading and why will you use it?

Ans:- Lazy loading modules help us decrease the startup to load the application. With lazy loading our application does not need to load everything at once, it only needs to load what the user expects to see when the app first loads. Modules that are lazily loaded will only be loaded when the user navigates to their routes.

Q46:- What is FormGroup and FormControl?

Ans:- It is used to create an angular reactive form. FormGroup is used with FormControl and FormArray. The role of FormGroup is to track the value and validation state of the form control.

Q47:- Angular is a Framework or platform?

Ans:- It’s both a platform and a framework. When you use it for web applications, you may call it a framework. when you develop a mobile application using any available resources like NativeScript, Cordova, Ionic, etc. and you use angular and in that term, angular is a platform.

Q48:- What is Bootstrapping?

Ans:- Bootstrapping is a technique of initializing or loading our Angular application. The Angular takes the following steps to load our first view.

Index.html loads
Angular, Third-party libraries & Application loads
Main.ts the application entry point
Root Module
Root Component
Template

Q49:- What is an NgRx store?

Ans:- Ngrx is a group of Angular libraries for reactive extensions. Ngrx/Store implements the Redux pattern using the well-known RxJS observables.

Q50:- How would I restrict access to routes?

Ans:- The trick to restricting the access to your private routes is to use canActivate property exposed by the router in Angular.
canActivate takes in a guard function where you can implement a logic that will decide whether or not to activate the route.