1. What is Angular? Why was it introduced? [1]
Angular was introduced to create Single Page applications. This framework brings structure and consistency to web applications and provides excellent scalability and maintainability.
Angular is an open-source JavaScript framework entirely written in TypeScript. It uses HTML syntax to express your application's components clearly.
2. What is TypeScript? [1]
TypeScript is a superset of JavaScript that offers excellent consistency. It is highly recommended, as it provides some syntactic sugar and makes the code base more comfortable to understand and maintain. Ultimately, TypeScript code compiles down to JavaScript that can run efficiently in any environment.
3. What are Single Page Applications (SPA)? [1]
Single-page applications are web applications that load once with new features just being mere additions to the user interface. It does not load new HTML pages to display the new page's content, instead generated dynamically. This is made possible through JavaScript's ability to manipulate the DOM elements on the existing page itself. A SPA approach is faster, thus providing a seamless user experience.
4. What are decorators in Angular? [1]
Decorators are a design pattern or functions that define how Angular features work. They are used to make prior modifications to a class, service, or filter. Angular supports four types of decorators, they are:
Class Decorators
Property Decorators
Method Decorators
Parameter Decorators
5. What are Annotations in Angular? [1]
Annotations in Angular create an annotation array. They are the metadata set in the class that reflects the metadata library.
6. What are Directives in Angular? [1]
Directives are attributes that allow the user to write new HTML syntax specific to their applications. They execute whenever the Angular compiler finds them in the DOM. Angular supports three types of directives.
Component Directives
Structural Directives
Attribute Directives
7. What is an AOT compilation? What are its advantages? [1]
The Ahead-of-time (AOT) compiler converts the Angular HTML and TypeScript code into JavaScript code during the build phase, i.e., before the browser downloads and runs the code.
Some of its advantages are as follows.
Faster rendering
Fewer asynchronous requests
Smaller Angular framework download size
Quick detection of template errors
Better security
8. What are Pipes in Angular? [1]
Pipes are simple functions designed to accept an input value, process, and return as an output, a transformed value in a more technical understanding. Angular supports several built-in pipes. However, you can also create custom pipes that cater to your needs.
Some key features include:
Pipes are defined using the pipe “|” symbol.
Pipes can be chained with other pipes.
Pipes can be provided with arguments by using the colon (:) sign.
9. What is the PipeTransform interface? [1]
As the name suggests, the interface receives an input value and transforms it into the desired format with a transform() method. It is typically used to implement custom pipes.
10. What are Pure Pipes? [1]
These pipes are pipes that use pure functions. As a result of this, a pure pipe doesn't use any internal state, and the output remains the same as long as the parameters passed stay the same. Angular calls the pipe only when it detects a change in the parameters being passed. A single instance of the pure pipe is used throughout all components.
11. What are Impure Pipes? [1]
For every change detection cycle in Angular, an impure pipe is called regardless of the change in the input fields. Multiple pipe instances are created for these pipes. Inputs passed to these pipes can be mutable.
12. What is view encapsulation in Angular? [1]
View encapsulation defines whether the template and styles defined within the component can affect the whole application or vice versa. Angular provides three encapsulation strategies:
Emulated - styles from the main HTML propagate to the component.
Native - styles from the main HTML do not propagate to the component.
None - styles from the component propagate back to the main HTML and therefore are visible to all components on the page.
13. Explain the lifecycle hooks in Angular [1]
In Angular, every component has a lifecycle. Angular creates and renders these components and also destroys them before removing them from the DOM. This is achieved with the help of lifecycle hooks. Here's the list of them -
ngOnChanges() - Responds when Angular sets/resets data-bound input properties.
ngOnInit() - Initialize the directive/component after Angular first displays the data-bound properties and sets the directive/component's input properties/
ngDoCheck() - Detect and act upon changes that Angular can't or won't detect on its own.
ngAfterContentInit() - Responds after Angular projects external content into the component's view.
ngAfterContentChecked() - Respond after Angular checks the content projected into the component.
ngAfterViewInit() - Respond after Angular initializes the component's views and child views.
ngAfterViewChecked() - Respond after Angular checks the component's views and child views.
ngOnDestroy - Cleanup just before Angular destroys the directive/component.
14. What is String Interpolation in Angular? [1]
String Interpolation is a one-way data-binding technique that outputs the data from TypeScript code to HTML view. It is denoted using double curly braces. This template expression helps display the data from the component to the view.
{{ data }}
15. What is Eager and Lazy loading? [1]
Eager loading is the default module-loading strategy. Feature modules under Eager loading are loaded before the application starts. This is typically used for small size applications.
Lazy loading dynamically loads the feature modules when there's a demand. This makes the application faster. It is used for bigger applications where all the modules are not required at the start of the application.
16. What are components? [2]
Components are the most basic UI building block of an Angular app, which form a tree of Angular components. These components are a subset of directives. Unlike directives, components always have a template, and only one component can be instantiated per element in a template. Let's see a simple example of Angular component.
17. What is a module? [2]
Modules are logical boundaries in your application and the application is divided into separate modules to separate the functionality of your application
The NgModule decorator has five important (among all) options:
The imports option is used to import other dependent modules. The BrowserModule is required by default for any web based angular application.
The declarations option is used to define components in the respective module.
The bootstrap option tells Angular which Component to bootstrap in the application.
The providers option is used to configure a set of injectable objects that are available in the injector of this module.
The entryComponents option is a set of components dynamically loaded into the view.
18. What is a data binding? [2]
Data binding is a core concept in Angular and allows to define communication between a component and the DOM, making it very easy to define interactive applications without worrying about pushing and pulling data. There are four forms of data binding(divided as 3 categories) which differ in the way the data is flowing.
From the Component to the DOM:
Interpolation: {{ value }}: Adds the value of a property from the component
- Name: {{ user.name }}
- Address: {{ user.address }}
Property binding: [property]=”value”: The value is passed from the component to the specified property or simple HTML attribute
From the DOM to the Component: Event binding: (event)=”function”: When a specific DOM event happens (eg.: click, change, keyup), call the specified method in the component
Two-way binding: Two-way data binding: [(ngModel)]=”value”: Two-way data binding allows to have the data flow both ways. For example, in the below code snippet, both the email DOM input and component email property are in sync
19. What is metadata? [2]
Metadata is used to decorate a class so that it can configure the expected behavior of the class. The metadata is represented by decorators
Class decorators, e.g. @Component and @NgModule
import { NgModule, Component } from '@angular/core';
@Component({
selector: 'my-component',
template: '
',
})
export class MyComponent {
constructor() {
console.log('Hey I am a component!');
}
}
@NgModule({
imports: [],
declarations: [],
})
export class MyModule {
constructor() {
console.log('Hey I am a module!');
}
}
Property decorators Used for properties inside classes, e.g. @Input and @Output
import { Component, Input } from '@angular/core';
@Component({
selector: 'my-component',
template: '
'
})
export class MyComponent {
@Input()
title: string;
}
Method decorators Used for methods inside classes, e.g. @HostListener
import { Component, HostListener } from '@angular/core';
@Component({
selector: 'my-component',
template: '
'
})
export class MyComponent {
@HostListener('click', ['$event'])
onHostClick(event: Event) {
// clicked, `event` available
}
}
Parameter decorators Used for parameters inside class constructors, e.g. @Inject, @Optional
import { Component, Inject } from '@angular/core';
import { MyService } from './my-service';
@Component({
selector: 'my-component',
template: '
'
})
export class MyComponent {
constructor(@Inject(MyService) myService) {
console.log(myService); // MyService
}
}
20. What is angular CLI? [2]
Angular CLI(Command Line Interface) is a command line interface to scaffold and build angular apps using nodejs style (commonJs) modules. You need to install using below npm command,
npm install @angular/cli@latest
Below are the list of few commands, which will come handy while creating angular projects
Creating New Project: ng new
Generating Components, Directives & Services: ng generate/g The different types of commands would be,
ng generate class my-new-class: add a class to your application
ng generate component my-new-component: add a component to your application
ng generate directive my-new-directive: add a directive to your application
ng generate enum my-new-enum: add an enum to your application
ng generate module my-new-module: add a module to your application
ng generate pipe my-new-pipe: add a pipe to your application
ng generate service my-new-service: add a service to your application
Running the Project: ng serve
21. What is the difference between constructor and ngOnInit? [2]
The Constructor is a default method of the class that is executed when the class is instantiated and ensures proper initialisation of fields in the class and its subclasses. Angular, or better Dependency Injector (DI), analyses the constructor parameters and when it creates a new instance by calling new MyClass() it tries to find providers that match the types of the constructor parameters, resolves them and passes them to the constructor.
ngOnInit is a life cycle hook called by Angular to indicate that Angular is done creating the component.
Mostly we use ngOnInit for all the initialization/declaration and avoid stuff to work in the constructor. The constructor should only be used to initialize class members but shouldn't do actual "work". So you should use constructor() to setup Dependency Injection and not much else. ngOnInit() is better place to "start" - it's where/when components' bindings are resolved.
export class App implements OnInit{
constructor(private myService: MyService){
//called first time before the ngOnInit()
}
ngOnInit(){
//called after the constructor and called after the first ngOnChanges()
//e.g. http call...
}
}
22. What is a service? [2]
A service is used when a common functionality needs to be provided to various modules. Services allow for greater separation of concerns for your application and better modularity by allowing you to extract common functionality out of components.
Let's create a repoService which can be used across components,
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
@Injectable({ // The Injectable decorator is required for dependency injection to work
// providedIn option registers the service with a specific NgModule
providedIn: 'root', // This declares the service with the root app (AppModule)
})
export class RepoService{
constructor(private http: Http){
}
fetchAll(){
return this.http.get('https://api.github.com/repositories');
}
}
The above service uses Http service as a dependency.
23. What is dependency injection in Angular? [2]
Dependency injection (DI), is an important application design pattern in which a class asks for dependencies from external sources rather than creating them itself. Angular comes with its own dependency injection framework for resolving dependencies( services or objects that a class needs to perform its function).So you can have your services depend on other services throughout your application.
24. What is the purpose of *ngFor directive?
We use Angular *ngFor directive in the template to display each item in the list. For example, here we can iterate over a list of users:
{{ user }}
The user variable in the *ngFor double-quoted instruction is a template input variable.
25. What is the purpose of *ngIf directive? [2]
Sometimes an app needs to display a view or a portion of a view only under specific circumstances. The Angular *ngIf directive inserts or removes an element based on a truthy/falsy condition. Let's take an example to display a message if the user age is more than 18:
18">You are not eligible for student pass!
Note: Angular isn't showing and hiding the message. It is adding and removing the paragraph element from the DOM. That improves performance, especially in the larger projects with many data bindings.
26. What is interpolation? [2]
Interpolation is a special syntax that Angular converts into property binding. It’s a convenient alternative to property binding. It is represented by double curly braces({{}}). The text between the braces is often the name of a component property. Angular replaces that name with the string value of the corresponding component property.
Let's take an example,
{{title}}
In the example above, Angular evaluates the title and url properties and fills in the blanks, first displaying a bold application title and then a URL.
27. What is a parameterized pipe? [2]
A pipe can accept any number of optional parameters to fine-tune its output. The parameterized pipe can be created by declaring the pipe name with a colon ( : ) and then the parameter value. If the pipe accepts multiple parameters, separate the values with colons. Let's take a birthday example with a particular format(dd/MM/yyyy):
import { Component } from '@angular/core';
@Component({
selector: 'app-birthday',
template: `
Birthday is {{ birthday | date:'dd/MM/yyyy'}}
` // 18/06/1987
})
export class BirthdayComponent {
birthday = new Date(1987, 6, 18);
}
Note: The parameter value can be any valid template expression, such as a string literal or a component property.
28. How do you chain pipes? [2]
You can chain pipes together in potentially useful combinations as per the needs. Let's take a birthday property which uses date pipe(along with parameter) and uppercase pipes as below
import { Component } from '@angular/core';
@Component({
selector: 'app-birthday',
template: `
Birthday is {{ birthday | date:'fullDate' | uppercase}}
` // THURSDAY, JUNE 18, 1987
})
export class BirthdayComponent {
birthday = new Date(1987, 6, 18);
}
29. What is a bootstrapping module? [2]
Every application has at least one Angular module, the root module that you bootstrap to launch the application is called as bootstrapping module. It is commonly known as AppModule.
30. What are observables? [2]
Observables are declarative which provide support for passing messages between publishers and subscribers in your application. They are mainly used for event handling, asynchronous programming, and handling multiple values. In this case, you define a function for publishing values, but it is not executed until a consumer subscribes to it. The subscribed consumer then receives notifications until the function completes, or until they unsubscribe.
31. What is HttpClient and its benefits? [2]
Most of the Front-end applications communicate with backend services over HTTP protocol using either XMLHttpRequest interface or the fetch() API. Angular provides a simplified client HTTP API known as HttpClient which is based on top of XMLHttpRequest interface. This client is available from @angular/common/http package. You can import in your root module as below:
import { HttpClientModule } from '@angular/common/http';
32. How can you read full response? [2]
The response body doesn't or may not return full response data because sometimes servers also return special headers or status code, which are important for the application workflow. In order to get the full response, you should use observe option from HttpClient:
getUserResponse(): Observable> {
return this.http.get(
this.userUrl, { observe: 'response' });
}
Now HttpClient.get() method returns an Observable of typed HttpResponse rather than just the JSON data
33. What is RxJS? [2]
RxJS is a library for composing asynchronous and callback-based code in a functional, reactive style using Observables. Many APIs such as HttpClient produce and consume RxJS Observables and also uses operators for processing observables.
For example, you can import observables and operators for using HttpClient as below,
import { Observable, throwError } from 'rxjs';
import { catchError, retry } from 'rxjs/operators';
34. What is subscribing? [2]
An Observable instance begins publishing values only when someone subscribes to it. So you need to subscribe by calling the subscribe() method of the instance, passing an observer object to receive the notifications.
35. What is Angular Router? [2]
Angular Router is a mechanism in which navigation happens from one view to the next as users perform application tasks. It borrows the concepts or model of browser's application navigation. It enables developers to build Single Page Applications with multiple views and allow navigation between these views.
36. What is the purpose of base href tag? [2]
The routing application should add element to the index.html as the first child in the tag in order to indicate how to compose navigation URLs.
37. What is router outlet? [2]
The RouterOutlet is a directive from the router library and it acts as a placeholder that marks the spot in the template where the router should display the components for that outlet. Router outlet is used like a component,
38. What is activated route? [2]
ActivatedRoute contains the information about a route associated with a component loaded in an outlet. It can also be used to traverse the router state tree. The ActivatedRoute will be injected as a router service to access the information.
39. What is the purpose of Wildcard route? [2]
If the URL doesn't match any predefined routes then it causes the router to throw an error and crash the app. In this case, you can use wildcard route. A wildcard route has a path consisting of two asterisks to match every URL.
For example, you can define PageNotFoundComponent for wildcard route as below
{ path: '**', component: PageNotFoundComponent }
40. What is JIT? [2]
Just-in-Time (JIT) is a type of compilation that compiles your app in the browser at runtime. JIT compilation was the default until Angular 8, now default is AOT. When you run the ng build (build only) or ng serve (build and serve locally) CLI commands, the type of compilation (JIT or AOT) depends on the value of the aot property in your build configuration specified in angular.json. By default, aot is set to true.
41. What is zone? [2]
A Zone is an execution context that persists across async tasks. Angular relies on zone.js to run Angular's change detection processes when native JavaScript operations raise events,
42. What is the purpose of common module? [2]
The commonly-needed services, pipes, and directives provided by @angular/common module. Apart from these HttpClientModule is available under @angular/common/http.
43. What is Angular Ivy? [2]
Angular Ivy is a new rendering engine for Angular. You can choose to opt in a preview version of Ivy from Angular version 8.
44. What is lazy loading? [2]
Lazy loading is one of the most useful concepts of Angular Routing. It helps us to download the web pages in chunks instead of downloading everything in a big bundle. It is used for lazy loading by asynchronously loading the feature module for routing whenever required using the property loadChildren.
45. What are Http Interceptors? [2]
Http Interceptors are part of @angular/common/http, which inspect and transform HTTP requests from your application to the server and vice-versa on HTTP responses. These interceptors can perform a variety of implicit tasks, from authentication to logging.
46. What are the applications of HTTP interceptors? [2]
The HTTP Interceptors can be used for different variety of tasks,
Authentication
Logging
Caching
Fake backend
URL transformation
Modifying headers
47. What is an angular library? [2]
An Angular library is an Angular project that differs from an app in that it cannot run on its own. It must be imported and used in an app. For example, you can import or add service worker library to an Angular application which turns an application into a Progressive Web App (PWA).
48. What is Angular compiler? [2]
The Angular compiler is used to convert the application code into JavaScript code. It reads the template markup, combines it with the corresponding component class code, and emits component factories which creates JavaScript representation of the component along with elements of @Component metadata.
49. What is a provider? [2]
A provider is an instruction to the Dependency Injection system on how to obtain a value for a dependency(aka services created). The service can be provided using Angular CLI as below,
ng generate service my-service
The created service by CLI would be as below,
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root', //Angular provide the service in root injector
})
export class MyService {
}
50. How do you provide a singleton service?
There are two possible ways to provide a singleton service.
Set the providedIn property of the @Injectable() to "root". This is the preferred way(starting from Angular 6.0) of creating a singleton service since it makes your services tree-shakable.
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root',
})
export class MyService {
}
Include the service in root module or in a module that is only imported by root module. It has been used to register services before Angular 6.0.
@NgModule({
...
providers: [MyService],
...
})
51. What is a shared module? [2]
The Shared Module is the module in which you put commonly used directives, pipes, and components into one module that is shared(import it) throughout the application.
For example, the below shared module imports CommonModule, FormsModule for common directives and components, pipes and directives based on the need,
import { CommonModule } from '@angular/common';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { UserComponent } from './user.component';
import { NewUserDirective } from './new-user.directive';
import { OrdersPipe } from './orders.pipe';
@NgModule({
imports: [ CommonModule ],
declarations: [ UserComponent, NewUserDirective, OrdersPipe ],
exports: [ UserComponent, NewUserDirective, OrdersPipe,
CommonModule, FormsModule ]
})
export class SharedModule { }
52. What is the difference between Observables and Promises in Angular? [3]
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. |
53. What do you understand by RouterOutlet and RouterLink? [3]
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. Router outlet is used as a component.
Syntax:
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 router-link directive as below,
Syntax:
- <h1>Angular Routerh1>
- <nav>
- <a routerLink="/todosList" >List of todosa>
- <a routerLink="/completed" >Completed todosa>
- nav>
- <router-outlet>router-outlet>
54. By default, Angular uses client-side rendering for its applications. Is it possible to make an Angular application to render on the server-side? [3]
Yes, it is possible to make an Angular application to 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:
- Making an Angular application render on the server-side can provide a better user experience. By using this, first-time users can instantly see a view of the application. So, it can be used to provide better UI.
- It can lead to a better SEO for your application. The reason is that many search engines expect pages in plain HTML. So, Angular Universal can ensure that your content is available on every search engine, and it is good for better SEO.
- The server-side rendered applications load faster than normal pages. It is because the rendered pages are available to the browser sooner.
55. What do you understand by Angular bootstrapping? [3]
Angular bootstrapping is nothing but to allow developers to initialize or start the Angular application. Angular supports two types of bootstrapping:
- Manual bootstrapping
- Automatic 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.
================
1. https://www.simplilearn.com/tutorials/angular-tutorial/angular-interview-questions
2. https://github.com/sudheerj/angular-interview-questions
3. https://www.javatpoint.com/top-angular-interview-questions