Angular Interview Questions
First of all best of luck with your interview. hope this article will be helpful.
What is the design pattern of the angular framework?
The angular framework used Single Page Application design pattern.
What are Single page applications?
All necessary HTML, JavaScript, and CSS code is loaded in the browser and is not reloaded during use.
When users interact with the page, the application dynamically rewrites/updates
the current page rather than loading a new page from the server.
Examples of Single Page Application?
Gmail, Google Maps, Airbnb, Netflix, Pinterest, Paypal
What other library/framework uses a single-page application pattern?
Angular, Ember.js, Meteor.js,vuejs and React.
Pros of Single Page application?
- Fast response time.
- Pages did not reload when we navigate pages.
- Simple to build and debug an app.
- Easy deployment
- Frontend and backend independent.
Cons of Single Page application?
SEO-Related Struggling.the biggest drawback of SPAs,
until recently, is that most search engines didn’t support client-side rendering when crawling websites, and had trouble correctly indexing a SPA.
What are architecture patterns in Angular?
Angular’s architecture is built on components.
Types of components in angular?
- Smart or container components
- Dumb or presentation components
What is a smart Component?
- A smart component is a use case-specific component.
- Its responsibility is to interact with the service layer to retrieve data.
What is a Dumb Component?
- We don’t inject service into it. It doesn’t fetch data.
- Its responsibility is to present and render data.
How does Component communication work?
- Passing Data from URLs
- Parent to child component @Input()
- Child to a parent component @Output()
- Passing Data Through a Service Using Observables
- Uses a @ViewChild to get the reference to the child component
What is Property Binding?
Property Binding is a one-way data-binding technique.
<element [property]= 'typescript_property'>What is Event Binding?
Event binding is used to handle the events raised by the user actions like button click, mouse movement, keystrokes, etc
<element (click)= 'openLog()'>What is Two Way Binding?
<element [(open)]= 'openLog'>How many Life cycles of a component?
- Constructor: A default method that is called when the class is instantiated.
- ngOnChanges: Executes when a new component is created, when one of the bound properties with @Input changes, also it is the only hook that takes an argument when it is called which is called as SimpleChanges.
- ngOnInit: Called once the component is initialized. This doesn’t allow the component to be visible over the DOM. This runs just after the constructor.
- ngDoCheck: Runs when change detection runs. It also runs if there is no change and even if it is just an event that occurred, just in case to make sure there is something that has changed. (for eg: It will run after a button click event irrespective of whether it is making any change or not)
- ngAfterContentInit: This is called after content(ng-content) has been projected into the view.
- ngAfterContentChecked: This is called after every projected content has been checked.
- ngAfterViewInit: Called after the components view (and child view) has been initialized.
- ngAfterViewChecked: Called every time the view (and child view) has been checked.
Note: always remember the order of lifecycle hooks.
1. What is Eager Loading?
Feature modules under Eager Loading would be loaded before the application starts. This is the default module-loading strategy.
2. What is Lazy Loading?
Feature modules under Lazy Loading would be loaded on demand after the application starts. It helps to start applications faster.
3. What is Pre-Loading?
Feature Modules under Pre-Loading would be loaded automatically after the application starts.
What is an angular Http interceptor?
The angular interceptor is a medium connecting the backend and front-end applications. Whenever a request is made, the interceptors handle it in between.
UseCases of Interceptor?
- Loaders
- Url
- Headers
- Converting
- Error
- Notification
- Mockup Backend
- Profiling
- Authentication
- Caching
Can we have more than one interceptor in angular?
Yes, you can have multiple angular interceptors by changing the value of multi to true. This will inform the classes regarding the usage of the angular HTTP interceptors.
Does the order of interceptors matter?
Interceptors have a pre-defined order determined by the order in which they are declared. And, by default, they follow the same order, and so do the developers.
What Are Route Guards?
The Angular router’s navigation guards allow to grant or remove access to certain parts of the navigation.
Here are the 4 types of routing guards available:
CanActivate: Controls if a route can be activated.
CanActivateChild: Controls if children of a route can be activated.
CanLoad: Controls if a route can even be loaded. This becomes useful for feature modules that are lazy-loaded. They won’t even load if the guard returns false.
CanDeactivate: Controls if the user can leave a route. Note that this guard doesn’t prevent the user from closing the browser tab or navigating to a different address. It only prevents actions from within the application itself.
What is View Encapsulation?
It defines the idea that all the data and methods that operate on that data are kept private in a single unit (or class). It is like hiding the implementation detail from the outside world.
The following three strategies are provided by Angular to determine how styles are applied.
ViewEncapsulation.None
ViewEncapsulation.Emulated
ViewEncapsulation.ShadowDOM
ViewEncapsulation.None
the styles defined in one component affect the elements of the other components.
ViewEncapsulation.Emulated
The ViewEncapsulation.Emulated strategy in angular adds the unique HTML attributes to the component CSS styles and to the markup so as to achieve encapsulation.
ViewEncapsulation.ShadowDOM
The Shadow DOM is a scoped sub-tree of the DOM. It is attached to an element (called shadow host) of the DOM tree. The shadow dom does not appear as a child node of the shadow host when you traverse the main DOM.
What is Pipe in angular?
Pipes take data as input process on it and return data as output. Pipes are useful in a sense when the same transformation is used throughout the application. Pipes make it easy to add these transformations to your component template.
What are the types of Pipes
Get zeeshan khan’s stories in your inbox
Join Medium for free to get updates from this writer.
1: Pure pipes
2: Impure pipes
Pure Pipes:
A pure pipe uses a pure function or you can say when we have deterministic value. It is only called when Angular detects a change in the value of the parameters passed as input to a pipe. A pure pipe will cache the results of the previous value or inputs. A single instance of the pure pipe is used all over the components. Pure pipes invoke pure change in either the input value(String, number, boolean) or in the object reference(Date, Array, Object). By Default Pipes are pure.
/ Pipe
@Pipe({
name: 'filter',
pure: true ----> 'Default is true'
})Examples of Pure Pipes
Built-In Pipes
- JsonPipe.
- LowerCasePipe.
- UpperCasePipe.
- PercentPipe.
- SlicePipe.
What are Impure Pipes?
An impure pipe is called for every change detection cycle whether or not the value or parameter(s) changes. Multiple instances are created for impure pipes. Impure pipes are not reused. We can’t use cache in case of impure pipes.
/ Pipe
@Pipe({
name: 'filter',
pure: false ----> 'Default is true'
})Examples of Impure Pipes
1. Async Pipe
2. JsonPipe
3.SlicePipe
A Drawback of Impure Pipes?
Impure pipes execute every time the change detection runs regardless of input value has changed or not. So, now the code runs on every mouse or keyboard event; this may overuse system resources. If the pipe is heavy, it will degrade the application’s performance.
Chaining Pipes
using multiple pipes together is called chaining pipes.
You can use multiple value transformations by chaining pipes together. The pipes are combined by utilizing the same pipe operator ( | ), and every pipe can optionally have its own properties to alter its behavior.
Example of Chaining Pipes
{{ birthday | date | uppercase}}What Is Async Pipe?
Async Pipe is an impure pipe that automatically subscribes to an observable to emit the latest values. It not only subscribes to an observable, but it also subscribes to a promise and calls the then method. When the components get destroyed, it automatically unsubscribes them to reduce memory leaks.
Syntax of AsyncPipe
{{obj_expression | async}}Advantages of Async Pipe
- Async Pipe makes the rendering of data from observable and promises easier.
- For promises, it automatically calls the
thenmethod. - For observables, it automatically calls
subscribeandunsubscribe.
What are directives in Angular?
Directives are classes that add new behavior or modify the existing behavior to the elements in the template.
What are the types of directives?
- Component directive
- Structural directive
- Attribute directive
Component directive
Components are special directives in Angular. They are the directive with a template
Structural directive
Structural directives are used to change the DOM layout by adding and removing DOM elements.
Examples of structural directives are ngIf, ngFor, ngSwitch.
Note: All structural Directives are preceded by Asterix (*)symbol.
Attribute directive
Attribute directives are used to change the appearance or behavior of an element. Examples of attributes directives are ngStyle, ngClass, ngModel.
What is the difference between a directive and a component?
A component is a directive with an associated view (i.e. HTML to be rendered). All components are directives, but not all directives are components.
import { Component, HostListener, HostBinding, Directive, ElementRef } from '@angular/core';
@Directive({
selector: '[appHighlight]'
})
export class HighlightDirective {
constructor(el: ElementRef) {
el.nativeElement.style.backgroundColor = 'yellow';
}
}
@Component({
selector: 'app-root',
template: `
<div *ngIf='myBool' appHighlight>Hi there</div>
`,
styleUrls: ['./app.component.scss'],
})
export class AppComponent {
myBool:boolean = true;
}Definition of Angular Service
It is basically a class that has a well-defined purpose to do something.
@Injectable({ providedIn: "root" })
export class AppService {
}Why do we use @Injectable() decorator?
@Injectable() is not mandatory because it is just another way of defining a provider. Likewise, if you add @Injectable({providedIn: ‘root’}) to your service, you will not need to add the service to any provider’s property on any module or component.
What is the purpose of providing the Injectable decorator?
providedIn: Type<any> | 'root' | 'platform' | 'any' | nullWhat providedIn: ‘platform’ do?
@Injectable({ providedIn: "platform" })
export class AppService {
}Angular will create and provide a single shared instance of AppService to all Angular applications on the page. (This is only relevant in advanced use cases if you use a micro-frontends architecture.)
What providedIn: ‘root’ do?
@Injectable({ providedIn: "root" })
export class AppService {
}When you provide the service at the root level, Angular creates a single, shared instance of service and injects it into any class that asks for it. Registering the provider in the @Injectable() metadata also allows Angular to optimize an app by removing the service from the compiled app if it isn’t used.
What providedIn: ‘any’ do?
@Injectable({ providedIn: "any" })
export class AppService {
}Angular will create a single shared instance of AppService and provide it to all classes in eagerly-loaded modules.
However, each lazy-loaded module will provide its own, new, separate instance of AppService (that will then be only available in classes inside that module).
What providedIn:<ModuleName> do?
@Injectable({ providedIn: ModuleName })
export class AppService {
}Angular will only create an instance of service if <ModuleName> is loaded.
If <ModuleName> is eagerly loaded, that instance will be available to all other eagerly loaded modules from now on. (Note that this is effectively identical to providedIn: ‘root’.)
However, if <ModuleName> is lazy loaded, then this instance will be provided only for classes inside <ModuleName> whenever it happens to be loaded.
What providedIn:<ComponentName> do?
@Injectable({ providedIn: ComponentName })
export class AppService {
}Angular will create a new, fresh instance of service whenever <ComponentName> is instantiated.
This Service instance will only be provided for descendants of that specific <ComponentName> instance and will be destroyed as soon as the component instance is destroyed. (Note that this means that a new MyService will be created each time this component is rendered.)
What providedIn:<null> do?
@Injectable({ providedIn: "null" })
export class AppService {
}Service can only ever be instantiated by being added to providers array in a specific module or component.
Only Injectable Decorator?
@Injectable()f you just use Injectable decorator without providedin.you would have to write service’s name in respective Module’s providers Array.
What do providers array?
Provider Array with Module
@NgModule({
providers: [ServiceName],
})Provider Array With Component.
@Component({
providers: [ServiceName],
})This method of providing does not support tree-shaking. The service will always be included in the compilation. Adding ServiceName to the providers array will cause the injector to create and provide an entirely separate instance of it to classes in its scope.
which one is more suitable provider array or provideIn root?
To make tree-shaking most effective, you should aim to always use providedIn over the providers array.
List of All Angular Decorators
- Class decorators
- Property Decorators
- Method decorators
- Parameter decorators
Class decorators
@NgModule
@Component
@Injectable
@Directive
@Pipe
Property Decorators
@Input
@Output
@ContentChild & @ContentChildren
@ViewChild & @ViewChildren
@HostBinding
Method decorators
@HostListener
Parameter decorators
@Inject
@Host
@Self
@SkipSelf
What is @ViewChild in Angular?
The @ViewChild decorator is used to query a single DOM element from the DOM tree and lets you manipulate it.
What is @ViewChildren in Angular?
The @ViewChildren decorator is used to access multiple elements. The response of the element list will always be a QueryList.
What is HostBinding?
Host Binding binds a Host element property to a variable in the directive or component
import { Directive, HostBinding, OnInit } from '@angular/core'
@Directive({
selector: '[appHighLight]',
})
export class HighLightDirective implements OnInit {
@HostBinding('style.border') border: string;
ngOnInit() {
this.border="5px solid blue"
}
}What is HostListener?
HostListener Decorator listens to the DOM event on the host element. It also provides a handler method to run when that event occurs.
import { Directive, HostBinding, OnInit, HostListener } from '@angular/core'
@Directive({
selector: '[appHighLight]',
})
export class HighLightDirective implements OnInit {
@HostBinding('style.border') border: string;
ngOnInit() {
}
@HostListener('mouseover')
onMouseOver() {
this.border = '5px solid green';
console.log("Mouse over")
}
@HostListener('mouseleave')
onMouseLeave() {
this.border = '';
console.log("Mouse Leave")
}
}What is change detection in angular?
Change Detection means updating the view (DOM) when the data has changed.
Angular Change Detection Strategies
Angular provides you with two Change Detection Strategies, the default one and the onPush.
What is ChangeDetectionStrategy.Default?
In order to know whether the view should be updated, Angular needs to access the new value,
compare it with the old one and make the decision on whether the view should be updated.
By default, Angular makes no assumption on what the component depends upon.
So it has to be conservative and will check every time something may have changed,
this is called dirty checking.
What is ChangeDetectionStrategy.onPush?
When using the onPush strategy on the component, you basically say to Angular that it should not make any guess on when it needs to perform the check for change.







