1) What is Angular? / What do you know about Angular?
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.
2) What are some powerful features integrated into Angular?
Angular integrates some powerful features like declarative templates, end to end tooling, dependency injection and various other best practices that smoothens the development path.
3) What is the main purpose of Angular?
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 the front end developers in curating cross-platform applications. YouTubeTV is the most popular example that uses Angular.
4) What is the difference between AngularJS and Angular?
Let’s compare the features of AngularJS and Angular in a tabular form:
A list of differences between AngularJS and Angular-
Feature
AngularJS
Angular
Version
AngularJS was the very first version initially released in 2010. It was a browser-side JavaScript used within HTML code and created a revolution in web application development. It is popularly known as AngularJS.
The later Angular versions were a complete rewrite of AngularJS. For example, Angular 2 was initially released in 2016. There is nothing common between Angular2 and AngularJS except the core developer’s team. After that, Angular 6, Angular 7, Angular 8, Angular 9, and Angular 10 were released that are very similar to each other. These later versions are known as Angular.
Architecture
AngularJS supports the MVC design model.
Angular uses components and directives.
Supported Language
The recommended and supported language of AngularJS is JavaScript.
The recommended and supported language of Angular is TypeScript.
Expression Syntax
In AngularJS, a specific ng directive is required for the image/property and an event.
Angular uses () for event binding and [] for property binding.
Mobile Support
AngularJS doesn’t provide any mobile support.
Angular provides mobile support.
Dependency Injection
There is no concept of Dependency Injection in AngularJS.
Angular supports hierarchical Dependency Injection with uni-directional tree-based change detection.
Routing
In AngularJS, $routeprovider.when() is used for routing configs.
In Angular, @RouteConfig{(?)} is used for the routing config.
Structure
It is the first and basic version, so it is very easy to manage.
It has a very simplified structure that makes the development and maintenance of large applications very easy.
Speed
It is slower because of its limited features.
It is faster than AngularJS because of its upgraded features.
Support
It doesn’t provide support or new updates anymore.
It provides active support, and frequent new updates are made.
5) What are the biggest advantages of using Angular?
Following is the list of the biggest advantages of using the Angular framework:
Angular supports two-way data-binding.
It follows MVC pattern architecture.
It supports static templates and Angular template.
It facilitates you to add a custom directive.
It also supports RESTfull services.
Validations are supported in Angular.
Angular provides client and server communication.
It provides support for dependency injection.
It provides powerful features like Event Handlers, Animation, etc.
6) What do you understand by Angular expressions? How are Angular expressions different from JavaScript expressions?
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 }}
Following is a list of some differences between Angular expressions and JavaScript expressions:
- The most crucial difference between Angular expressions and JavaScript expressions is that the Angular expressions allow us to write JavaScript in HTML. On the other hand, the JavaScript expressions don’t allow.
- The Angular expressions are evaluated against a local scope object. On the other hand, the JavaScript expressions are evaluated against the global window object. We can understand it better with an example. Suppose we have a component named test:
import { Component, OnInit } from ‘@angular/core’;
@Component({
selector: ‘app-test’,
template: `
{{message}}
,
styleUrls: [‘./test.component.css’]
})
export class TestComponent implements OnInit {
message:string = ?Hello world?;
constructor() { }
ngOnInit() {
}
}
In the above example, we can see that the Angular expression is used to display the message property. In the present template, we are using Angular expressions, so we cannot access a property outside its local scope (in this case, TestComponent). This proves that Angular expressions are always evaluated based on the scope object rather than the global object.
- The Angular expressions can handle null and undefined, whereas JavaScript expressions cannot.
See the following JavaScript example:
JavaScript Test
After running the above code, you see undefined displayed on the screen. Although it’s not ideal to leave any property undefined, the user does not need to see this.
Now see the following Angular example:
import { Component, OnInit } from ‘@angular/core’;
@Component({
selector: ‘app-new’,
template: <h4>{{message}}</h4>
,
styleUrls: [‘./new.component.css’]
})
export class NewComponent implements OnInit {
message:object = {};
constructor() { }
ngOnInit() {
}
}
In the above example, you will not see undefined being displayed on the screen.
- In Angular expressions, we cannot use loops, conditionals, and exceptions. The difference which makes Angular expressions quite beneficial is the use of pipes. Angular uses pipes (known as filters in AngularJS) to format data before displaying it.
See this example:
import { Component, OnInit } from ‘@angular/core’;
@Component({
selector: ‘app-new’,
template: `
{{message | lowercase}}
,
styleUrls: [‘./new.component.css’]
})
export class NewComponent implements OnInit {
message:string = “HELLO JAVATPOINT”;
constructor() { }
ngOnInit() {
}
}
In the above example, we have used a predefined pipe called lowercase, which transforms all the letters in lowercase. If you run the above example, you will see the output displayed as “hello javatpoint”.
On the other hand, JavaScript does not have the concept of pipes.
7) What are templates in Angular?
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.
8) What is the difference between an Annotation and a Decorator in Angular?
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.
9) Why was Angular introduced as a client-side framework?
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 of data handling facilities across the views by jQuery. The need for a client-side framework like Angular was obvious that 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 by doing so.
10) How does an Angular application work?
Every Angular app contains a file named angular.json. This file contains all the configurations of the app. While building the app, the builder looks at this file to find the application’s entry point. See the structure of the angular.json file:
“build”: {
“builder”: “@angular-devkit/build-angular:browser”,
“options”: {
“outputPath”: “dist/angular-starter”,
“index”: “src/index.html”,
“main”: “src/main.ts”,
“polyfills”: “src/polyfills.ts”,
“tsConfig”: “tsconfig.app.json”,
“aot”: false,
“assets”: [
“src/favicon.ico”,
“src/assets”
],
“styles”: [
“./node_modules/@angular/material/prebuilt-themes/deeppurple-amber.css”,
“src/style.css”
]
}
}
When the application enters the build section, the options object’s main property defines the entry point of the application. The application’s entry point is main.ts, which creates a browser environment for the application to run and calls a function called bootstrapModule, which bootstraps the application.
These two steps are performed in the following order inside the main.ts file:
import { platformBrowserDynamic } from ‘@angular/platform-browser-dynamic’;
platformBrowserDynamic().bootstrapModule(AppModule)
In the above line of code, AppModule is getting bootstrapped.
The AppModule is declared in the app.module.ts file. This module contains declarations of all the components.
Below is an example of app.module.ts file:
import { BrowserModule } from ‘@angular/platform-browser’;
import { NgModule } from ‘@angular/core’;
import { AppComponent } from ‘./app.component’;
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule
],
providers: [],
entryComponents: [],
bootstrap: [AppComponent]
})
export class AppModule { }
In the above file, you can see that AppComponent is getting bootstrapped. It is defined in app.component.ts file. This file interacts with the webpage and serves data to it.
Below is an example of app.component.ts file:
import { Component } from ‘@angular/core’;
@Component({
selector: ‘app-root’,
templateUrl: ‘./app.component.html’,
styleUrls: [‘./app.component.css’]
})
export class AppComponent {
title = ‘angular’;
}
Each component is declared with three properties:
Selector – It is used to access the component.
Template/TemplateURL – It contains HTML of the component.
StylesURL – It contains component-specific stylesheets.
Now, Angular calls the index.html file. This file consequently calls the root component that is app-root. The root component is defined in app.component.ts.
See how the index.html file looks like:
Angular
The HTML template of the root component is displayed inside the tags.This is the way how every angular application works.
11) Why is Angular preferred over other frameworks? / What are some advantages of Angular over other frameworks?
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.
12) What are the different Lifecycle hooks of Angular? Explain them in short.
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.
Angular Interview questions
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 the above hooks we have described, the ngOnInit hook is the most often used hook. Let’s see how to use the ngOnInit hook. If you have to process a lot of data during component creation, it’s better to do it inside the ngOnInit hook rather than the constructor:
See the example:
import { Component, OnInit } from ‘@angular/core’;
@Component({
selector: ‘app-test’,
templateUrl: ‘./test.component.html’,
styleUrls: [‘./test.component.css’]
})
export class TestComponent implements OnInit {
constructor() { }
ngOnInit() {
this.processData();
}
processData(){
// Do something..
}
}
In the above code, you can see that we have imported OnInit, but we have used the ngOnInit function. This is how we can use the rest of the hooks as well.
13) What is AOT in Angular?
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. By compiling the application during the build process provides a faster rendering in the browser.
14) What is the reason for using the AOT compiler in Angular?
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.
15) What are the biggest advantages of AOT in Angular?
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.
16) What is JIT in Angular?
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.
17) What is the main difference between JIT and AOT in Angular?
Following are the main differences between JIT and AOT compiler in Angular:
Just-in-Time (JIT) compiler compiles our app in the browser at run-time while Ahead-of-Time (AOT) compiler is used to compile your app at build time on the server.
The JIT compilation runs by default when you run the ng build (build only), or ng serve (build and serve locally) CLI commands. This is used for development. On the other hand, we have to include the –aot option with the ng build or ng serve command for AOT compilation.
JIT and AOT are both two ways used to compile code in an Angular project. JIT compiler is used in development mode while AOT is used for production mode.
JIT is easy to use. We can easily implement features and debug in JIT mode because here we have a map file while AOT does not. On the other hand, the biggest advantage of using AOT for production is that it reduces the bundle size for faster rendering.
18) What is the concept of scope hierarchy 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 to other view controllers.
Following is the typical representation of a Scope Hierarchy:
Root $scope
$scope for Controller 1
$scope for Controller 2
…
..
.
$scope for Controller n
19) What are the main building blocks of an Angular application? Explain with the pictorial diagram of Angular architecture.
Following are the main building blocks of an Angular application. You can see them in the following picture:
Angular Interview questions
20) What is the difference between Observables and Promises in Angular?
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.
Let’s understand it by an example:
const observable = rxjs.Observable.create(observer => {
console.log(‘This is what inside an observable’);
observer.next(‘Hello JavaTpoint’);
observer.complete();
});
console.log(‘Before subscribing an Observable’);
observable.subscribe((message)=> console.log(message));
When you run the above Observable, you can see the following messages displayed in the following order:
Before subscribing an Observable
This is what inside an observable
Hello JavaTpoint
Here, you can see that observables are lazy. Observable runs only when someone subscribes to them. That’s why the message “Before subscribing an Observable” is displayed ahead of the message inside the observable.
Now see the example of a Promise:
const promise = new Promise((resolve, reject) => {
console.log(‘This is what written inside promise’);
resolve(‘Hello JavaTpoint’);
});
console.log(‘Before calling then method on Promise’);
greetingPoster.then(message => console.log(message));
When you run the above Promise, you will see the messages displayed in the following order:
This is what written inside Promise
Before calling then method on Promise
Hello JavaTpoint
Here, you can see that the message inside Promise is displayed first. This means that the Promise runs first, and then the method is called.
The next difference between them is that Promises are always asynchronous; even when the Promise is immediately resolved. On the other hand, an Observable can be both synchronous and asynchronous.
In the case of the above example, observable is synchronous. Let’s see the case where an observable can be asynchronous:
const observable = rxjs.Observable.create(observer => {
setTimeout(()=>{
observer.next(‘Hello JavaTpoint’);
observer.complete();
},3000)
});
console.log(‘Before calling subscribe on an Observable’);
observable.subscribe((data)=> console.log(data));
console.log(‘After calling subscribe on an Observable’);
When you run the above observable, you will see the messages in the following order:
Before calling subscribe on an Observable
After calling subscribe on an Observable
Hello JavaTpoint
22) What are directives in Angular?
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.
23) What were the main reasons behind introducing client-side frameworks like Angular?
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.
Note: We can also develop dynamic websites and SPAs (Single Page Applications) using VanillaJS, and jQuery but by doing so, the development process becomes slower.
24) What is Angular CLI?
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:
Creating New Project: ng new
Generating Components, Directives & Services: ng generate/g
Running the Project: ng serve
25) What is lazy loading in Angular?
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’
}
];
26) What is Angular Router?
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.
27) What do you understand by the router imports?
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 in the app module:
import { RouterModule, Routes } from ‘@angular/router’;
28) What are the different router events used in Angular Router?
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:
NavigationStart
RouteConfigLoadStart
RouteConfigLoadEnd
RoutesRecognized
GuardsCheckStart
ChildActivationStart
ActivationStart
GuardsCheckEnd
ResolveStart
ResolveEnd
ActivationEnd
ChildActivationEnd
NavigationEnd
NavigationCancel
NavigationError
29) What do you understand by RouterOutlet and RouterLink?
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:
Leave a Reply