Top 30 Angular Interview Questions with Answers for Beginners and Experienced Candidates

Here is the list of the most important and frequently asked top 30 angular interview questions with answers for the beginners and the experienced candidates.
Q1. What is Decorators in Angular?
The decorator allows us to decorate (add extra information) classes and function, similar to annotations in Java. They are just functions, to add metadata and properties to a class or function. It’s a feature available only in Typescript.
// Decorators Example
@Input()
@Output()
@Component()
@NgModule()
Q2. What is String interpolation in Angular?
String Interpolation is a special syntax that combines double curly braces {{ }}
to bind properties of the component class. We can write JavaScript expressions inside double curly braces, and also we can invoke component methods inside double curly braces.
{{ 1+1 }}
{{ yourCompPropertyName }}
{{ componentMethod() }}
Q3. How to protect routes from unauthorized users in Angular?
We can use the guard in angular to protect routes. The Auth Guard has two methods canActivate
and canActivateChildren
, both returns a boolean based on the authentication condition we have, for example, we can check whether there is a token stored in service or localStorage.
- The
canActivate
method – protect the particular route, where we add the auth guard in the route declaration. - The
canActivateChildren
– protect the child routes of a route where we add the auth guard in the route declaration.
Q4: Types of Directives in Angular?
Angular has 3 types of directives.
- Component Directive
- Structural Directive
- Attribute Directive
1. Component Directives
All the components in angular are actually directives itself. Directives that have templates are components in Angular.
2. Structural Directives
Structural Directives modify/manipulates the DOM elements based on conditions or inputs. Some of the built-in structural directives are *ngIf
, *ngFor
, *ngSwtich
.
3. Attribute Directives
Attribute Directives change the appearance or behavior of an element, component, or another directive. Some of the built-in attribute directives are ngClass
, ngStyle
etc.
Q5: What are templates in Angular?
Angular templates are written in HTML that contains angular specific syntax like interpolation (double curly braces), attributes, etc to bind the properties or methods from the component logic which results in rendering the page dynamically.
We can write angular templates in component.html and specify the template file in templateUrl
property of @Component
decorator.
@Component({
selector: 'app-home',
templateUrl: './home.component.html'
})
We can also write inline angular templates using template
property of @Component
decorator.
@Component({
selector: 'app-home'
template: `<h1>{{ title }}</h1>`
})
Q6: How to Access DOM in Angular?
Angular has decorators and reference types like @ViewChild
, @ViewChildren
, @ContentChild
, @ContentChildren
and ElementRef
to access/manipulate the DOM.
The @ViewChild
will access the single reference of an element based on the template reference variable. The @ViewChildren
will access the list of reference (QueryList
).
@Component({
selector: 'app-dom-test',
template: `
<div #child1>First Child</div>
<div>Second Child</div>
`
})
export class TestComponent implements OnInit {
@ViewChild("child1") firstChild: ElementRef;
constructor() { }
ngOnInit() {
console.log(this.firstChild.nativeElement);
}
}
The @ContentChild
and @ContentChildren
will access the element coming from ng-content
.
// Child Component
@Component({
selector: "component-a",
template: `<ng-content></ng-content>`
})
export class ComponentA {
@ContentChild("contentChild") contentChild: ElementRef;
ngOnInit() {
console.log(this.contentChild.nativeElement);
}
}
// Parent Component
@Component({
selector: 'app-test',
template: `
<component-a>
<div #contentChild>Content Child 1</div>
<div>Content Child 2</div>
</component-a>
`
})
export class TestComponent implements OnInit {}
Q7: What is ng-template in Angular?
The ng-template
is an angular template element, the content inside the ng-template
is a part of the overall template. We can reuse the same template in multiple places.
Angular under the hood makes use of ng-template
in all the structural directives.
<div class="lessons-list" *ngIf="showLoader">
Loading...
</div>
// the above code will be converted into
<ng-template [ngIf]="showLoader">
<div>Loading...</div>
</ng-template>
Q8: Types of compilation in Angular
Angular has two types of compilation JIT (Just in time compiler) and AOT (ahead of time compiler)
- AOT (Ahead-of-Time) compiles your app and libraries at build time. This is the default since Angular 9.
- JIT (Just-in-Time) which compiles your app in the browser at runtime. This was the default until Angular 8.
Q9: What are Observables in RxJS?
An Observable is a function that can return a stream of data to an observer (subscribers) over time, this can either be synchronously or asynchronously.
The Observables are lazy, it needs observers to emit data. If there are no observers (subscribers) for an observable, then the logic inside the observable won’t execute.
Q10: What are the differences between Observables and Promises?
- Observables are lazy but promises are not lazy. Observables need subscribers in order to execute the code whereas Promises will execute immediately.
- The Observables can handle multiple values but promises can handle only a single value. It can emit streams of data.
- You can cancel observable by using the unsubscribe method but you can not cancel a promise. For example, you can cancel an API call which is in progress in observable but you can’t do the same with promises.
- The RxJS observables have many built-in operators such as maps, filter, debounce, etc to modify the data before it reaches the observers (subscribers) but promises don’t have any operators.
Q11: What is HTTP interceptors in Angular?
HTTP interceptors are a type of service in Angular. It has a method called intercept()
, that is used to modify the request and response of all the API calls. For example, adding JWT token in the HTTP header for all the API calls.
@Injectable()
export class HeaderInterceptor implements HttpInterceptor {
intercept(httpRequest: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const token = 'youtJWTToken';
return next.handle(httpRequest.clone({ setHeaders: { token } }));
}
}
Q12: What is ng-content in Angular?
The ng-content
is used to create configurable and customized components. Most of the published angular libraries making use of ng-content to make their components more configurable. Most popularly known as Content Projection.
You can send a component or HTML element in between a component tag, in the component.html you can render the content sent in between the tag using ng-content
.
// component.html (app-home)
<div class="header">
<ng-content select="h1"></ng-content>
</div>
<div class="body">
<ng-content select=".body"></ng-content>
</div>
<div class="footer">
<ng-content select="footer"></ng-content>
</div>
// using app-home
<app-home>
<h1>Title</h1>
<div class="body">Lorem ipsum...</div>
<footer>footer links</footer>
</app-home>
You can also render specific content by using the select
property of ng-content
. This way you can create more customized reusable components.
Q13: What is Pipe in Angular?
Pipes are simple functions that transform data. Adding pipes in template expressions helps to modify/transform data like currency, date, etc.
Angular has many built-in pipes such as:
DatePipe
: Formats a date value according to locale rules.UpperCasePipe
: Transforms text to all upper case.LowerCasePipe
: Transforms text to all lower case.CurrencyPipe
: Transforms a number to a currency string, formatted according to locale rules.DecimalPipe
: Transforms a number into a string with a decimal point, formatted according to locale rules.PercentPipe
: Transforms a number to a percentage string, formatted according to locale rules.
<p>{{ someDateProperty | date:"MM/dd/yy" }} </p>
// output: Friday, April 15, 2020
Q14: Difference between Pure pipes and Impure pipes in Angular
A pure pipe is called when Angular detects a change in the value or the parameters passed to a pipe.
An impure pipe is called for every change detection cycle no matter whether the value or parameter changes.
Q15: What is Change Detection in Angular?
Whenever a property of the component changed, The angular runs change detection to update the view. By default, angular runs change detection on every property change, DOM events, AJAX calls, timers, etc.
The Change Detection in Angular happens by checking the property’s current value with the old value, if the values are different angular will update/re-render the view.
Q16: What is ChangeDetection onPush Strategy in Angular?
The onPush
Change detection strategy is used to restrict the change detection that is to run change detection only when the input (@Input()
) properties of the component value changes.
It’s helps to detect value changes inside an object or array without creating a new reference. We can use change detection markForCheck()
method to tell angular to run change detection.
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class HomeComponent {
@Input() foodList = [];
constructor(private cd: ChangeDetectorRef) {}
// you have a button to add new food, just pushing a new value to an array won't trigger change detection.
// so, we are making use of markForCheck method to insist angular to run change detection.
addFood(food) {
this.foodList.push(food);
this.cd.markForCheck();
}
}
Q17: What are all the ways to Share Data between Angular Components?
Share Data from Parent Component to Child Component:
We can share data from parent component to child component by declaring a property with @Input()
decorator in the child component. We can then send the data from parent to child using that property binding.
//child-component.ts
@Input() name: string;
//parent-component.html
<app-child [name]="'Dwayne Johnson'"></app-child>
Share Data from Child Component to Parent Component:
We can share data from the child component to the parent component by using @Output()
and EventEmitter
. We can listen for the event in the parent component to get the data from the child.
//child-component.ts
@Output() changed: new EventEmitter<boolean>();
submit() {
this.changed.emit(true);
}
// parent-component.ts
<app-child (changed)="save($event)"></app-child>
save(value) {
console.log(value);
}
// $event is the value emitted from the child component.
Share Data between unrelated Components:
We can share data between unrelated components using services. Services are singleton objects, so we can make use of it to maintain the state of the application. You can create a BehaviourSubject
in the service, and emit values, whatever components subscribed to that subject will receive the values.
export class SharedDataService {
constructor(){}
//Using any
public editDataDetails: any = [];
public subject = new Subject<any>();
private messageSource = new BehaviorSubject(this.editDataDetails);
currentMessage = this.messageSource.asObservable();
changeMessage(message: string) {
this.messageSource.next(message)
}
}
//Set value in component 1
this.sharedDataService.changeMessage("message here");
//Get value in component 2
selectedMessage:any;
ngOnInit() {
this.sharedDataService.currentMessage.subscribe(message => (this.selectedMessage= message));
}
Q18: How do you access a query params form a route in Angular Component?
We need to inject ActivatedRoute
in the component constructor and then we can subscribe to the queryParams
observable in the ActivatedRoute
to get the values from query params as an object.
constructor(private activatedRoute: ActivatedRoute) {
this.activatedRoute.queryParams.subscribe((params: Params) => {
console.log(params);
});
}
Q19: What are all the life cycle methods available in Angular?
Angular has several life cycle methods for a component from creating a view to removing the view. Here are the life cycle methods in an order:
ngOnChanges( )
: This lifecycle method called whenever one or more input properties of the component changes. This is the first lifecycle method triggered by angular in the component. It receives a SimpleChanges
object containing the previous and current values of the property.
ngOnInit( )
: When angular creating a component, it invokes the ngOnInit
method. We can do things like calling an API and initializing the property values or subscribing to an observable inside this ngOnInit
lifecycle method.
ngDoCheck( )
: It gets called after ngOnChanges
and ngOnInit
and is used to detect and act on changes that cannot be detected by Angular. We can implement our change detection algorithm in this hook.
ngAfterContentInit( )
: It gets called after the first ngDoCheck
hook. This hook responds after the content gets projected inside the component.
ngAfterContentChecked( )
: It gets called after ngAfterContentInit
and every subsequent ngDoCheck. It responds after the projected content is checked.
ngAfterViewInit( )
: It responds after a component’s view, or a child component’s view is initialized. We can use this life cycle method to access the DOM element.
ngAfterViewChecked( )
: It gets called after ngAfterViewInit
, and it responds after the component’s view, or the child component’s view is checked.
ngOnDestroy( )
: It gets called just before Angular destroys the component. This hook can be used to clean up the code, detach event handlers, and unsubscribe observables.
Q20: What is Dependency Injection in Angular?
Dependency Injection is an application design pattern. Angular has its own dependency injection pattern, they are services and objects which have common functionalities.
Dependency Injection is a coding pattern in which a class (components, directives) asks for dependencies (services) from external sources rather than creating them itself.
Q21: What is Angular Universal?
A normal Angular application executes in the browser, rendering pages in the DOM in response to user actions. Angular Universal executes on the server, generating static application pages that later get bootstrapped on the client. This means that the application generally renders more quickly, giving users a chance to view the application layout before it becomes fully interactive.
- Better User Experience: Allows users to see the view of the application instantly without waiting for the whole JS to download.
- Better SEO: Angular Universal ensures that the content is available on every search engine leading to better SEO.
- Loads Faster: Render pages are available to the browsers sooner, so the server-side application loads faster.
Q22: What are Services in Angular?
Angular Services are singleton objects that get instantiated only once throughout the application lifecycle. In Angular, services play a major role in dependency injection. It’s used to store data throughout the application lifecycle. We can use services to write common functionalities for the application.
Angular service is used to share business logic, models, or data and functions with various components/directives of an Angular application.
We need to provide the services in the providers
array of @NgModule
. Then we can inject the services into the constructor of the components and directives which are under that module.
Q23: What is ViewEncapsulation in Angular and mention it’s types?
ViewEncapsulation determines whether the CSS styles defined in a particular component will affect the entire application or not. Angular supports 3 types of ViewEncapsulation:
- Emulated – This is the default option, Angular adds an attribute to the element of the component and updates the CSS with that attribute so other components won’t get affected.
- ShadowDOM – Using Shadow DOM to encapsulate styles.
- None – No encapsulation will be provided, component style will be global.
Q24: What is Event Binding in Angular?
Event Binding in Angular allows us to listen for events such as click, keystrokes, mouse events, etc.
Angular event binding syntax consists of a target event name within parentheses on the left of an equal sign, and a quoted template statement on the right.
<button (click)="someMethod($event)">Click Here</button>
The $event
contains the event object if it’s a DOM native event. If it’s a custom event triggered by EventEmitter
, then the value of $event would be object, string, boolean, etc.
Q25: What is Two-way Binding in Angular?
Two way binding in Angular allows us to share data between a component class and template.
Angular offers a special two-way data binding syntax for this purpose, [()]
. The [()]
syntax combines the brackets of property binding, []
, with the parentheses of event binding, ()
.
<input type="text" [(ngModel)]="username" />
Q26: What is Template Reference Variable in Angular?
Template reference variable is used to reference a DOM element in template. It can also refer to a directive (which contains a component), an element, TemplateRef.
You can define a template reference variable using the (#) symbol in the template.
<button #submitBtn (click)="submit()">Submit</button>
Angular assigns each template reference variable a value based on where you declare the variable:
- If you declare the variable on a component, the variable refers to the component instance.
- If you declare the variable on a standard HTML tag, the variable refers to the element.
- If you declare the variable on an
<ng-template>
element, the variable refers to theTemplateRef
instance, which represents the template. - If the variable specifies a name on the right-hand side, such as
#var="ngModel"
the variable refers to the directive or component on the element with a matchingexportAs
name.
Q27: How to retry a failed HTTP Request in Angular?
The RxJS library has a retry()
operator which automatically subscribes to the failed observables. By using, retry()
operator we can retry failed HTTP Request.
fetchData() {
return this.http.get<Config>(this.configUrl)
.pipe(
retry(5), // retry a failed request up to 5 times
catchError(this.handleError) // then handle the error
);
}
Q28: How do you display 404 page in Angular?
We can use **
wildcard route in the route definition. The router selects this route if the requested URL doesn’t match any of the paths earlier in the list and sends the user to the relevant component based on our route definition.
const routes: Routes = [
{ path: 'first-component', component: FirstComponent },
{ path: 'second-component', component: SecondComponent },
{ path: '**', component: PageNotFoundComponent }, // Wildcard route for a 404 page
];
Q29: What is FormArray in Angular?
The FormArray
in Reactive Forms is used to create a group of form controls or form groups. It’s used to create dynamic forms, like adding/removing form controls/form groups to the form.
To learn more about FormArray
in reactive forms, checkout this tutorial. Add / Remove Multiple Input Fields Dynamically using Form Array in Angular Reactive Forms
Q30: What is Angular Ivy?
Angular Ivy is a default angular compiler and runtime from version 9. Before Ivy, Angular has the so-called View Engine Compiler.
Benefits of using Angular Ivy:
- Better Build Time – Ivy compiles only the changed code, already compiled codes won’t be compiled again unless the code gets changed.
- Smaller Bundle Size – Angular Ivy has a tree-shaking method that is to remove unused codes while compilation. It reduces the bundle size after the compilation.
- Faster Testing – Angular Ivy,
TestBed
doesn’t recompile components between tests unless a component has been manually overridden, which allows it to avoid recompilation between the grand majority of tests. Previously,TestBed
recompiles all the components. - Improved Type Checking
- Improved Build Errors
Conclusion:
Hope, the above questions and answers helped you to prepare for your angular interview. If you have faced questions other then those listed here or if you want to add new questions to this list to help others, please make a comment here with the question. Thank you!