If you want to work in Angular field. Going over the Angular technical interview questions, on the other hand, isn't exactly a bed of roses. The following list of Angular interview questions and answers can assist you whether you are a candidate seeking a job or a recruiter looking for the best Angular. You can use it to model other questions based on this pattern or answer questions that are similar to this one.
Angular is one of the most popular JavaScript frameworks developed and maintained by Google. It is an open-source front-end web framework based on TypeScript. It is most suited for developing enterprise web applications because its code is reusable and maintainable.
Angular integrates some powerful features like declarative templates, end-to-end tooling, dependency injection, and various other best practices that smoothen the development path.
The main purpose of using Angular is to create fast, dynamic, and scalable web applications. We can create these applications very easily with Angular using components and directives.
Angular was started as a SPA (Single-Page-Application) framework, and now it supports dynamic content based on different users through dependency injection. It provides a platform for easy development of web-based applications and empowers front-end developers in curating cross-platform applications. YouTubeTV is the most popular example that uses Angular.
Following is the list of the biggest advantages of using the Angular framework:
Angular expressions are code snippets that are used to bind application data to HTML. Angular resolves the expressions, and the result is returned to where the expression is written. Angular expressions are usually written in double braces: {{ expression }} similar to JavaScript.
Syntax:
{{ expression }}
In Angular, templates contain Angular-specific elements and attributes. These are written with HTML and combined with information coming from the model and controller, which are further rendered to provide the user's dynamic view.
In Angular, annotations are the "only" metadata set of the class using the Reflect Metadata library. They are used to create an "annotation" array. On the other hand, decorators are the design patterns used for separating decoration or modification of a class without actually altering the original source code.
Before the introduction of Angular, web developers used VanillaJS and jQuery to develop dynamic websites. Later, when the websites became more complex with added features and functionality, it was hard for them to maintain the code. Along with this, there were no provisions for data handling facilities across the views by jQuery. The need for a client-side framework like Angular was obvious which can make life easier for the developers by handling separation of concerns and dividing code into smaller bits of information (components).
Client-side frameworks like Angular facilitate developers to develop advanced web applications like Single-Page-Application. These applications can also be developed using VanillaJS, but the development process becomes slower doing so.
Due to the following features, Angular is preferred over other frameworks:
Extraordinary Built-in Features: Angular provides several out-of-the-box built-in features like routing, state management, RxJS library, Dependency Injection, HTTP services, etc. That's why the developers do not need to look for the above-stated features separately.
Declarative UI: Angular has declarative UI. It uses HTML to render the UI of an application as it is a declarative language. It is much easier to use than JavaScript.
Long-term Google Support: Angular is developed and maintained by Google. Google has a long-term plan to stick with Angular and provide support.
When the Angular components are created, they enter their lifecycle and remain when they are destroyed. Angular Lifecycle hooks are used to check the phases and trigger changes at specific phases during the entire duration.
ngOnChanges( ): This method is called when one or more input properties of the component are changed. The hook receives a SimpleChanges object containing the previous and current values of the property.
ngOnInit( ): This is the second lifecycle hook. It is called once, after the ngOnChanges hook. It is used to initialize the component and sets the input properties of the component.
ngDoCheck( ): This hook is called after ngOnChanges and ngOnInit and is used to detect and act on changes that Angular cannot detect. In this hook, we can implement our change detection algorithm.
ngAfterContentInit( ): This hook is called after the first ngDoCheck hook. This hook responds after the content gets projected inside the component.
ngAfterContentChecked( ): This hook is called after ngAfterContentInit and every subsequent ngDoCheck. It responds after the projected content is checked.
ngAfterViewInit( ): This hook is called after a component's view or initializing a child component's view.
ngAfterViewChecked( ): This hook is called after ngAfterViewInit. It responds after the component's view or when the child component's view is checked.
ngOnDestroy( ): This hook is called just before Angular destroys the component. This is used to clean up the code and detach event handlers.
In Angular, AOT stands for Ahead-Of-Time compiler. It is used to convert your Angular HTML and TypeScript code into efficient JavaScript code during the build phase before the browser downloads and runs that code. Compiling the application during the build process provides a faster rendering in the browser.
An Angular application is made of several components and their HTML templates. Because of these Angular components and templates, the browsers are not able to understand them directly. So, Angular applications require a compilation process before they run in a browser. That's why AOT compilers are required.
Following are the advantages of using the AOT compiler in Angular:
The rendering is faster: When we use the AOT compiler, the browser gets a pre-compiled version of the application to download. Here, the browser loads executable code to render the application immediately, without waiting to compile the app first.
The Angular framework's download size is smaller: AOT facilitates you not to download the Angular compiler if the app is already compiled. The compiler is roughly half of Angular itself, so omitting it dramatically reduces the application payload.
Fewer asynchronous requests: The compiler is used to inline external HTML templates and CSS style sheets within the application JavaScript so, it eliminates separate AJAX requests for those source files.
Detect template errors earlier: While using the AOT compiler, developers can easily detect and report template binding errors during the build step before users can see them.
Better security: AOT provides better security because it compiles HTML templates and components into JavaScript files before they are served to the client. Because there are no templates to read and no risky client-side HTML or JavaScript evaluation, so the chances for injection attacks are very rare.
In Angular, JIT stands for Just-in-Time compiler. The JIT compiler provides a dynamic translation or run-time compilation, which provides a way of executing computer code that involves compilation during the execution of a program at run time rather than before execution.
Following are the main differences between JIT and AOT compiler in Angular:
Angular provides the $scope objects into a hierarchy that is typically used by views. This is called the scope hierarchy in Angular. It has a root scope that can further contain one or several scopes called child scopes.
In a scope hierarchy, each view has its own $scope. Hence, the variables set by a view's view controller will remain hidden from other view controllers.
In Angular, as soon as we make a promise, the execution takes place, but this is not the case with observables because they are lazy. It means nothing happens until a subscription is made.
Promise | Observable |
---|---|
It emits a single value. | It emits multiple values over a period of time. |
Not Lazy | Lazy. An observable is not called until we subscribe to the observable. |
We can not cancel it. | We can cancel it by using the unsubscribe() method. |
Observable provides operators like map, forEach, filter, reduce, retry, retryWhen, etc. |
A directive is a class in Angular that is declared with a @Directive decorator. Every directive has its own behavior, and you can import them into various components of an application.
Before Angular was introduced, the web developers used VanillaJS and jQuery to develop dynamic websites, but the biggest drawback of these technologies is that as the logic of the website grew, the code became more and more complex to maintain. For websites and applications that use complex logic, developers had to put in extra effort to maintain the separation of concerns for the app. Also, jQuery did not provide facilities for data handling across views.
The client-side frameworks like Angular were introduced to overcome the above problems. It provides developers many benefits over VanilaJS and jQuery by providing a new feature called components for handling separation of concerns and dividing code into smaller bits of information.
Client-side frameworks such as Angular facilitate developers to develop advanced web applications like Single-Page-Applications. So, the main reasons behind introducing Angular were to create fast, dynamic, and scalable web applications easily.
Angular CLI is a short form for Angular Command Line Interface. It is a command-line interface to scaffold and build angular apps using node.js style modules.
To use Angular CLI, we have to install it by using the following npm command:
npm install @angular/cli@latest
Following is a list of some useful commands which would be very helpful while creating angular projects:
Lazy loading is one of the most powerful and useful concepts of Angular Routing. It makes the web pages easy to download by downloading them in chunks instead of downloading everything in a big bundle. Lazy loading facilitates asynchronously loading the feature module for routing whenever required using the property loadChildren.
See the following example where we are going to load both Employee and Order feature modules lazily.
See the example:
const routes: Routes = [
{
path: 'employees',
loadChildren: () => import('./employees/employees.module').then(module => module.EmployeesModule)
},
{
path: 'orders',
loadChildren: () => import('./orders/orders.module').then(module => module.OrdersModule)
},
{
path: '',
redirectTo: '',
pathMatch: 'full'
}
];
Angular Router is a mechanism that facilitates users to navigate from one view to the next as users perform application tasks. It follows the concept model of browser's application navigation.
The Angular Router, representing a particular component view for a given URL, is not part of Angular Core. It is available in a library named @angular/router, and we have to import the required router components. This process is called router imports.
See the following example of how we can import them into the app module:
import { RouterModule, Routes } from '@angular/router';
A RouterOutlet is a directive from the router library that acts as a placeholder. It marks the spot in the template where the Router should display the components for that outlet. A router outlet is used as a component.
Syntax:
<router-outlet></router-outlet>
On the other hand, a RouterLink is a directive on the anchor tags that gives the router control over those elements. Since the navigation paths are fixed, you can assign string values to the router-link directive as below,
Syntax:
<h1>Angular Router</h1>
<nav>
<a routerLink="/todosList" >List of todos</a>
<a routerLink="/completed" >Completed todos</a>
</nav>
<router-outlet></router-outlet>
During each navigation, the Router emits navigation events through the Router.events property. It allows us to track the lifecycle of the route.
Following is the list of different router events in sequence:
The RouterLinkActive is a directive used to toggle CSS classes for active RouterLink bindings based on the current RouterState. i.e., the Router will add CSS classes when this link is active and remove them when the link is inactive.
For example, you can add them to RouterLinks as follows:
<h1>Angular Router</h1>
<nav>
<a routerLink="/todosList" routerLinkActive="active">List of todos</a>
<a routerLink="/completed" routerLinkActive="active">Completed todos</a>
</nav>
<router-outlet></router-outlet>
The RouterState is a tree of activated routes. Every node in this tree knows about the "consumed" URL segments, the extracted parameters, and the resolved data. We can access the current RouterState from anywhere in the application by using the Router service and the routerState property.
@Component({templateUrl:'template.html'})
class MyComponent {
constructor(router: Router) {
const state: RouterState = router.routerState;
const root: ActivatedRoute = state.root;
const child = root.firstChild;
const id: Observable<string> = child.params.map(p => p.id);
//...
}
}
Most front-end applications use either XMLHttpRequest interface or the fetch() API to communicate with backend services over HTTP protocol. For the same purpose, Angular provides a simplified client HTTP API known as HttpClient. This is based on top of the XMLHttpRequest interface. This HttpClient is available in the @angular/common/http package, which you can import into your root module as follows:
import { HttpClientModule } from '@angular/common/http';
Following are some of the crucial advantages of HttpClient:
Yes, it is possible to make an Angular application render on the server side. Angular provides a technology called Angular Universal that can be used to render applications on the server side.
The crucial advantages of using Angular Universal are as follows:
Error is when the request fails on the server or fails to reach the server due to network issues. In this condition, HttpClient returns an error object instead of a successful response. To resolve this issue, we must handle the component by passing the error object as a second callback to the subscribe() method.
See the following example to understand how we handle the component:
fetchUser() {
this.userService.getProfile()
.subscribe(
(data: User) => this.userProfile = { ...data }, // success path
error => this.error = error // error path
);
}
You can write an error message to give the user some meaningful feedback instead of displaying the raw error object returned from HttpClient.
Angular bootstrapping is nothing but allowing developers to initialize or start the Angular application. Angular supports two types of bootstrapping:
Manual bootstrapping: Manual bootstrapping provides more control to developers and facilitates them regarding how and when they need to initialize the Angular app. It is useful when professionals wish to perform other tasks and operations before Angular compiles the page.
Automatic bootstrapping: As the name specifies, automatic bootstrapping is started automatically to start the Angular app. The developers need to add the ng-app directive to the application's root if they want Angular to bootstrap the application automatically. Angular loads the associated module once it finds the ng-app directive and, further, compiles the DOM.
The digest cycle process in Angular is the process that is used to monitor the watchlist to track changes in the watch variable value. There is a comparison between the present and the previous versions of the scope model values in each digest cycle.
A Component is a directive that uses shadow DOM to create encapsulated visual behavior. Usually, components are used to create UI widgets by breaking up the application into smaller parts. In short, we can say that a component (@component) is a directive-with-a-template.
A list of the major differences between a Component and a Directive in Angular:
Component | Directive |
---|---|
Components are generally used for creating UI widgets. | Directives are generally used for adding behavior to an existing DOM element. |
We use @Component meta-data annotation attributes to register a component. | We use @Directive meta-data annotation attributes to register directives. |
It is used to break up the application into smaller parts called components. | It is used to design re-usable components. |
Only one component is allowed to be used per DOM element. | Multiple directives are allowed to be used per DOM element. |
@View decorator or templateurl/template is mandatory in a component. | A Directive doesn't use View. |
A component is used to define pipes. | In a directive, it is not possible to define Pipes |
The MVVM architecture or Model-View-ViewModel architecture is a software architectural pattern that provides a facility to developers to separate the development of the graphical user interface (the View) from the development of the business logic or back-end logic (the Model). By using this architecture, the view is not dependent on any specific model platform.
The Angular MVVM architecture consists of the following three parts:
Model: The Model consists of the structure of an entity and specifies the approach. In simple words, we can say that the model contains data of an object.
View: The View is the visual layer of the application. It specifies the structure, layout, and appearance of what a user sees on the screen. It displays the data inside the Model, represents the model, and receives the user's interaction with the view in the form of mouse clicks, keyboard input, screen tap gestures, etc., and forwards these to the ViewModel via the data binding properties. In Angular terms, the View contains the HTML template of a component.
ViewModel: The ViewModel is an abstract layer of the application. It is used to handle the logic of the application. It also manages the data of a model and displays it in the view. View and ViewModel are connected with two-way data-binding. If you make any changes in the view, the ViewModel takes a note and changes the appropriate data inside the model.
The AsyncPipe is used to subscribe to an observable or promise and return the latest value it has emitted. When a new value is emitted, the pipe marks the component that has been checked for changes.
See the following example where a time observable continuously updates the view for every 2 seconds with the current time.
Example:
@Component({
selector: 'async-observable-pipe',
template: `<div><code>observable|async</code>:
Time: {{ time | async }}</div>`
})
export class AsyncObservablePipeComponent {
time = new Observable(observer =>
setInterval(() => observer.next(new Date().toString()), 2000)
);
}
In Angular, services are singleton objects that get instantiated only once during the lifetime of an application. An Angular service contains methods that are used to maintain the data throughout the life of an application. Angular services are used to organize as well as share business logic, models, or data and functions with various components of an Angular application.
Angular services offer some functions that can be invoked from an Angular component, such as a controller or directive.
Constructor is a default method in TypeScript classes that are normally used for initialization purpose. On the other hand, the ngOnInit is specifically an Angular method and is used to define Angular bindings. Even though constructors are getting called first, it is always preferred to move all of your Angular bindings to the ngOnInit method.
See the following example of how we can use ngOnInit by implementing the OnInit interface as follows:
export class App implements OnInit{
constructor(){
//called first time before the ngOnInit()
}
ngOnInit(){
//called after the constructor and called after the first ngOnChanges()
}
}
Observable: An observable is a unique object just like a promise that is used to manage async code. Observables are not part of the JavaScript language so the developers have to rely on a popular Observable library called RxJS. The observables are created using the new keyword.
See a simple example of observable to understand it better:
import { Observable } from 'rxjs';
const observable = new Observable(observer => {
setTimeout(() => {
observer.next('This is a message from Observable!');
}, 1000);
});
Observer: Any object that has to be notified when the state of another object changes is called an observer. An observer is an interface for push-based notifications delivered by an Observable.
See the structure of an observer:
interface Observer<T> {
closed?: boolean;
next: (value: T) => void;
error: (err: any) => void;
complete: () => void;
}
The handler that implements the observer interface for receiving observable notifications is passed as a parameter for observable as follows:
myObservable.subscribe(myObserver);
In Angular, we can categorize data binding types into three categories distinguished by the direction of data flow. These data binding categories are:
Let's see their possible binding syntax:
Data direction | Syntax | Type |
---|---|---|
From the source-to-view(One-way data binding) | 1. {{expression}} 2. [target]="expression" 3. bind-target="expression" | Interpolation, Property, Attribute, Class, Style |
From view-to-source(One-way data binding) | 1. (target)="statement" 2. on-target="statement" | Event |
View-to-source-to-view(Two-way data binding) | 1. [(target)]="expression" 2.bindon-target="expression" | Two-way data binding |
In Angular, the by default tendency of NgModules is eagerly loaded. It means that as soon as the app loads, all the NgModules are loaded, whether or not they are immediately necessary. That's why lazy loading is required. Lazy loading is mandatory for large apps with lots of routes. This design pattern makes the app load NgModules when they are only required. Lazy loading helps keep initial bundle sizes smaller, which in turn helps decrease load times.
Filters are an essential part of Angular that helps in formatting the expression value to show it to the users. We can easily add filters to services, directives, templates, or controllers. We can also create personalized filters as per requirements. These filters allow us to organize the data in such a way that only the data that meets the respective criteria are displayed. Filters are placed after the pipe symbol ( | ) while used in expressions.
A list of various types of filters used in Angular:
If you create an Angular application where multiple components need to have similar functionalities, you have to do it by adding this functionality individually to every component. This is not a very easy task. Directives are used to cope with this situation. Here, we can create a directive with the required functionality and then import the directive to components that require this functionality.
String interpolation and property binding are parts of data-binding in Angular. Data-binding is a feature of Angular, which is used to provide a way to communicate between the component (Model) and its view (HTML template). There are two ways of data binding, one-way data binding, and two-way data binding. In Angular, data from the component can be inserted inside the HTML template. Any changes in the component will directly reflect inside the HTML template in one-way binding, but vice-versa is not possible. On the other hand, it is possible in two-way binding.
String interpolation and property binding both are examples of one-way data binding. They allow only one-way data binding.
String Interpolation: String interpolation uses the double curly braces {{ }} to display data from the component. Angular automatically runs the expression written inside the curly braces. For example, {{ 5+5 }} will be evaluated by Angular, and the output will be 10. This output will be displayed inside the HTML template.
Property Binding: Property binding is used to bind the DOM properties of an HTML element to a component's property. In property binding, we use the square brackets [ ] syntax.
Dependency injection is an application design pattern that is implemented by Angular. It is used to form the core concepts of Angular. Dependencies are services in Angular which have some specific functionality. Various components and directives in an application can need these functionalities of the service. Angular provides a smooth mechanism by which these dependencies are injected into components and directives.
You can demonstrate the navigation between different routes in an Angular app in the following way. See the following code to demonstrate navigation in an Angular app named "My First App."
import from "@angular/router";
.
.
.
@Component({
selector: 'app-header',
template: `
<nav class="navbar navbar-light bg-faded">
<a class="navbar-brand" (click)="goHome()">My First App</a>
<ul class="nav navbar-nav">
<li class="nav-item">
<a class="nav-link" (click)="goHome()">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" (click)="goSearch()">Search</a>
</li>
</ul>
</nav>
})
class HeaderComponent {
constructor(private router: Router) {}
goHome() {
this.router.navigate(['']);
}
goSearch() {
this.router.navigate(['search']);
}
}
There are mainly three types of directives in Angular:
Component Directives: The component directives are used to form the main class in directives. To declare these directives, we have to use the @Component decorator instead of the @Directive decorator. These directives have a view, a stylesheet, and a selector property.
Structural directives: These directives are generally used to manipulate DOM elements. The structural directive has a ' * ' sign before them. We can apply these directives to any DOM element.
Following are some examples of built-in structural directives:
*ngIf Structural Directive: *ngIf is used to check a Boolean value and if it's truthy, the div element will be displayed.
<div *ngIf="isReady" class="display_name">
{{name}}
</div>
*ngFor Structural Directive: *ngFor is used to iterate over a list and display each item of the list.
<div class="details" *ngFor="let x of details" >
<p>{{x.name}}</p>
<p> {{x.address}}</p>
<p>{{x.age}}</p>
</div>
Attribute Directives: The attribute directives are used to change the look and behavior of a DOM element. Let's create an attribute directive to understand it well:
This is how we can create a custom directive:
Go to the command terminal, navigate to the directory of the angular app and type the following command to generate a directive:
This will generate the following directive. Manipulate the directive to look like this:
import { Directive, ElementRef } from '@angular/core';
@Directive({
selector: '[appYellowBackground]'
})
export class YellowBackgroundDirective {
constructor(el:ElementRef) {
el.nativeElement.style.backgroundColor = "yellow";
}
}
Now, you can easily apply the above directive to any DOM element:
<p appYellowBackground>Hello JavaTpoint</p>
Submitted questions and answers are subject to review and editing, and may or may not be selected for posting, at the sole discretion of w3Sniff.
Get Started