Angular Interview Questions

Angular Interview Questions

  • What Is Angular 4?

Angular is a most popular web development framework for developing mobile apps as well as desktop applications. Angular framework is also utilized in the cross platform mobile development called IONIC and so it is not limited to web apps only.
Angular is an open source framework written and maintained by angular team at Google and the Father of Angular is Misko Hevery. Misko Hevery – Agile Coach at Google, Attended Santa Clara University and Lives in Saratoga, CA. Angular is written in TypeScript and so it comes with all the capabilities that typescript offers.
You don’t worry about the TypeScript versions. The compiler manages to the versioning related problems and Angular team working with Traceur compiler team to provide the support to build some extensions.

Angular Interview Questions

  • What Is Angular CLI?

The Angular CLI is a tool to initialize, develop, scaffold and maintain Angular applications.
Installation – npm install -g @angular/cli
Example – CREATE your project directory as like below

F:\AngularTestApp\DemoApp>npm install -g @angular/cli

C:\Users\Anil\AppData\Roaming\npm\ng -> C:\Users\Anil\AppData\Roaming\npm\node_modules\@angular\cli\bin\ng
C:\Users\Anil\AppData\Roaming\npm
`– @angular/cli@1.5.0
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@^1.0.0 (node_modules\@angular\cli\node_modules\chokidar\node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.1.2: wanted {“os”:”darwin”,”arch”:”any”} (current: {“os”:”win32″,”arch”:”x64″})

The Angular CLI will add reference to components, directives and pipes automatically in “app.module”.

  • How To Update Angular CLI?

If you’re using Angular CLI lesser version, uninstall angular-cli package and install new versions.
npm uninstall -g angular-cli
npm uninstall –save-dev angular-cli

Global package –

npm uninstall -g @angular/cli
npm cache clean
npm install -g @angular/cli@latest

Local project package –

rm -rf node_modules dist # use rmdir /S/Q node_modules dist in Windows Command Prompt; use rm -r -fo node_modules,dist in Windows PowerShell
npm install –save-dev @angular/cli@latest
npm install

Some Additional Commands –
ng new
ng serve
ng generate
ng lint
ng test
ng e2e
ng build
ng get
ng set
ng doc
ng eject
ng xi18n and so on.

Angular Interview Questions

  • What’s New in Angular 4?

Angular 4 contains some additional Enhancement and Improvement. Consider the following enhancements.

Smaller & Faster Apps
View Engine Size Reduce
Animation Package
NgIf and ngFor Improvement
Template
NgIf with Else
Use of AS keyword
Pipes
HTTP Request Simplified
Apps Testing Simplified
Introduce Meta Tags
Added some Forms Validators Attributes
Added Compare Select Options
Enhancement in Router
Added Optional Parameter
Improvement Internationalization

 

Angular Interview Questions

  • Why Angular 4?

It Makes work easier compared with angular 2 and other models.
Writing code is lots of cleaner and lesser.
It Improve the execution performance for Data binding and so on.
It has included Animations features.
In Angular 4, no need to apply observable methods because Angular analyses every page’s DOM and it is automatically modifies to page’s DOM.
It is also supported by Visual Studio, IntelliJ, And NET IDES and so on.
Migration is really very soft and cleaner.
And So On..

 

  • How to Setup Angular 4 Development Environment?

Angular 4 Setup Guide –

Step 1. Setup the Development Environment
Install Node.js and NPM -If you are not already have on your machine!
Then you Install the Angular CLI globally!

npm install -g @angular/cli

Step 2 – Navigate to project directory and Create a new project!

$ cd ~/Dev/
$ mkdir appDir && cd appDir
$ ng new my-app

Note – ng new takes time to run!

Step 3 – Navigate to project & Run Local Server!
$ cd /path/to/your/newly/created/app/

like
$ cd ~/Dev/appDir/my-app/
$ ng serve

Open local host – http://localhost:53865/

Note –The ng serve command is used to launches the server, watches your files and rebuilds the app as you make changes to those files!

Step 4 -Edit Project and Save files

– Open file in appDir/my-app/src/app/app.component.ts, EDIT and SAVE

import { Component } from ‘@angular/core’;

@Component({
selector: ‘app-root’,
templateUrl: ‘./app.component.html’,
styleUrls: [‘./app.component.css’]
})
export class AppComponent {
title = ‘Welcome you in Angular 4!’;
}

Step 5. Test build
ng build

  • What Is Bootstrapping in Angular 4 and 5?

a.The Bootstrap is the root AppComponent that Angular creates and inserts into the “index.html” host web page.

 

index.html –
<!doctype html>

MyApp
You can put more than one component tree on a host web page, that’s not typical. Most of the applications have only one component tree and they bootstrap a single root component and you can call the one root component anything you want but most developers call it AppComponent.

The bootstrapping process creates the components listed in the bootstrap array and inserts each one into the browser (DOM).

The Angular Module (NgModules) helps us to organize an application into connected blocks of functionality.

The NgModule properties for the minimum “AppModule” generated by the CLI which are follow as –

Declarations — Use to declare the application components.
Imports —Every application must import BrowserModule to run the app in a browser.
Providers — There are none to start.
Bootstrap — This is a root AppComponent that Angular creates and inserts into the index.html host web page.

app.module.ts –

import { BrowserModule } from ‘@angular/platform-browser’;
import { NgModule } from ‘@angular/core’;

import { AppComponent } from ‘./app.component’;
import { LoginComponent } from ‘./login/login.component’;
import { SignupComponent } from ‘./signup/signup.component’;

@NgModule({
declarations: [
AppComponent,
LoginComponent,
SignupComponent
],
imports: [
BrowserModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }

By default Bootstrap file is created in the folder “src/main.ts” and “main.ts” file is very stable. Once you have set it up, you may never change it again and its looks like –

import { enableProdMode } from ‘@angular/core’;
import { platformBrowserDynamic } from ‘@angular/platform-browser-dynamic’;

import { AppModule } from ‘./app/app.module’;
import { environment } from ‘./environments/environment’;

if (environment.production) {
enableProdMode();
}

platformBrowserDynamic().bootstrapModule(AppModule)
.catch(err => console.log(err));

Angular Interview Questions

  • How to Upgrade Web Applications from Angular 2 to Angular 4?

a.Angular 2 apps will work using Angular 4 without changing anything. Angular 4 offers lots-of enhancements i.e.

Angular 4 is smaller than Angular 2
Angular 4 is faster than Angular 2
Angular 4 has enhanced *ngFor and *ngIf
Angular 4 has more meaningful errors
Overriding a template in Angular v4
Angular 4 has great Animations
Angular 4 Installation Process on Windows –

npm install @angular/common@latest @angular/compiler@latest @angular/compiler-cli@latest @angular/core@latest @angular/forms@latest @angular/http@latest @angular/platform-browser@latest @angular/platform-browser-dynamic@latest @angular/platform-server@latest @angular/router@latest @angular/animations@latest typescript@latest –save

Angular 4 Installation Process on Linux/Mac-

npm install @angular/{common,compiler,compiler-cli,core,forms,http,platform-browser,platform-browser-dynamic,platform-server,router,animations}@latest typescript@latest –save

If you faced any error in Linux application update from angular 2 to angular 4

Delete your node modules
Update your dependency In Linux Environment and execute the command

Angular Interview Questions

  • How to Set Http Request Header in Angular 4 and Angular 2?

The HTTP Interceptors are used to Set Http Headers Request in Angular 4 using the import from “@angular/common/http”. The HTTP Interceptors are available in Angular 4.x versions.

The HTTP Interceptors are not supported in Angular 2. We are creating the HttpClient Injectable class to achieve this. You can see the below examples for set http headers request with and without HTTP interceptors.

 

  • What Is the Use of Interceptors in Angular 4?

The Interceptors is a common used to set default headers for all responses.

Example 1 – For Angular 4

Set Headers Http Request Using Http Interceptors –

The HTTP Interceptors are now available via using the new HttpClient from angular/common/http in the Angular 4.x versions.

Steps 1 – Writing an interceptor for adds a header for every request!

import {HttpEvent, HttpInterceptor, HttpHandler, HttpRequest} from ‘@angular/common/http’;

export class AddHttpHeaderInterceptor implements HttpInterceptor {
intercept(req: HttpRequest, next: HttpHandler): Observable<HttpEvent> {
// Get the auth header from the service.
const authHeader = ‘token_value’;
const clonedReq = req.clone({headers: req.headers.set(‘Authorization’, authHeader)});
return next.handle(clonedReq);
}
}

Steps 2 – Providing your interceptor!

– After creating the interceptor, we need to register it using the HTTP_INTERCEPTORS in the @NgModule()

import { HTTP_INTERCEPTORS } from ‘@angular/common/http’;
@NgModule({
providers: [{
provide: HTTP_INTERCEPTORS,
useClass: AddHttpHeaderInterceptor,
multi: true,
}],
})

export class AppModule {}

Example 2- For Angular 2

Set Headers Http Request without HTTP Interceptors –

Steps 1 – We are creating the HttpClient Injectable class.

import {Injectable} from ‘@angular/core’;
import {Http, Headers} from ‘@angular/http’;

@Injectable()
export class HttpClient {
constructor(private http: Http) {}

createAuthHeader(headers: Headers) {
headers.append(‘Content-Type’, ‘application/json’);
headers.append(‘Authorization’, ‘Basic ‘ + btoa(‘user-name:password’));
}
get(url) {
let headers = new Headers();
this.createAuthHeader(headers);
return this.http.get(url, {headers: headers})
}

post(url, data) {
let headers = new Headers();
this.createAuthHeader(headers);

return this.http.post(url, data, {headers: headers});
}

put(url, data) {
let headers = new Headers();
this.createAuthHeader(headers);
return this.http.put(url, data, {headers: headers});
}
}

Steps 2 – Injecting the HttpClient object in the Component

import { HttpClient } from ‘../http-client’;
export class userComponent {
constructor(http: HttpClient) {
this.http = httpClient;
}

getUsers() {
this.http.get(url).subscribe(data =>{console.log(data); });
}
addUsers(user) {
this.http.post(url, user).subscribe(data =>{console.log(data); });
}
}

 

Angular Interview Questions

  • How to Upgrade Web Applications from Angular 2 to Angular 4?

a. Angular 2 apps will work using Angular 4 without changing anything. Angular 4 offers lots-of enhancements i.e.

Angular 4 is smaller than Angular 2
Angular 4 is faster than Angular 2
Angular 4 has enhanced *ngFor and *ngIf
Angular 4 has more meaningful errors
Overriding a template in Angular v4
Angular 4 has great Animations
Angular 4 Installation Process on Windows –

npm install @angular/common@latest @angular/compiler@latest @angular/compiler-cli@latest @angular/core@latest @angular/forms@latest @angular/http@latest @angular/platform-browser@latest @angular/platform-browser-dynamic@latest @angular/platform-server@latest @angular/router@latest @angular/animations@latest typescript@latest –save

Angular 4 Installation Process on Linux/Mac-

npm install @angular/{common,compiler,compiler-cli,core,forms,http,platform-browser,platform-browser-dynamic,platform-server,router,animations}@latest typescript@latest –save

If you faced any error in Linux application update from angular 2 to angular 4

Delete your node modules
Update your dependency In Linux Environment and execute the command

  • How to Set Http Request Header in Angular 4 and Angular 2?

The HTTP Interceptors are used to Set Http Headers Request in Angular 4 using the import from “@angular/common/http”. The HTTP Interceptors are available in Angular 4.x versions.

The HTTP Interceptors are not supported in Angular 2. We are creating the HttpClient Injectable class to achieve this. You can see the below examples for set http headers request with and without HTTP interceptors.

 

Angular Interview Questions

  • What Is the Use of Interceptors in Angular 4?

a.The Interceptors is a common used to set default headers for all responses.

Example 1 – For Angular 4

Set Headers Http Request Using Http Interceptors –

The HTTP Interceptors are now available via using the new HttpClient from angular/common/http in the Angular 4.x versions.

Steps 1 – Writing an interceptor for adds a header for every request!

import {HttpEvent, HttpInterceptor, HttpHandler, HttpRequest} from ‘@angular/common/http’;

export class AddHttpHeaderInterceptor implements HttpInterceptor {
intercept(req: HttpRequest, next: HttpHandler): Observable<HttpEvent> {
// Get the auth header from the service.
const authHeader = ‘token_value’;
const clonedReq = req.clone({headers: req.headers.set(‘Authorization’, authHeader)});
return next.handle(clonedReq);
}
}

Steps 2 – Providing your interceptor!

– After creating the interceptor, we need to register it using the HTTP_INTERCEPTORS in the @NgModule()

import { HTTP_INTERCEPTORS } from ‘@angular/common/http’;
@NgModule({
providers: [{
provide: HTTP_INTERCEPTORS,
useClass: AddHttpHeaderInterceptor,
multi: true,
}],
})

export class AppModule {}

Example 2- For Angular 2

Set Headers Http Request without HTTP Interceptors –

Steps 1 – We are creating the HttpClient Injectable class.

import {Injectable} from ‘@angular/core’;
import {Http, Headers} from ‘@angular/http’;

@Injectable()
export class HttpClient {
constructor(private http: Http) {}

createAuthHeader(headers: Headers) {
headers.append(‘Content-Type’, ‘application/json’);
headers.append(‘Authorization’, ‘Basic ‘ + btoa(‘user-name:password’));
}
get(url) {
let headers = new Headers();
this.createAuthHeader(headers);
return this.http.get(url, {headers: headers})
}

post(url, data) {
let headers = new Headers();
this.createAuthHeader(headers);

return this.http.post(url, data, {headers: headers});
}

put(url, data) {
let headers = new Headers();
this.createAuthHeader(headers);
return this.http.put(url, data, {headers: headers});
}
}

Steps 2 – Injecting the HttpClient object in the Component

import { HttpClient } from ‘../http-client’;
export class userComponent {
constructor(http: HttpClient) {
this.http = httpClient;
}

getUsers() {
this.http.get(url).subscribe(data =>{console.log(data); });
}
addUsers(user) {
this.http.post(url, user).subscribe(data =>{console.log(data); });
}
}
this.http.post(url, user).subscribe(data =>{console.log(data); });
}
}

Angular Interview Questions

  • What Is the forRoot Method?

a. The forRoot is a static method and it’s very easy for developers to configure the modules and the best example is – RouterModule.forRoot.

The RouterModule also offers a forChild. It’s also a static method and use to configure the routes of lazy-loaded modules. The forRoot and forChild are the traditional names for methods that configure services in root.

Example –
import { NgModule } from ‘@angular/core’;
import { RouterModule, Routes } from ‘@angular/router’;
import { HttpModule } from ‘@angular/http’;
import { FormsModule, ReactiveFormsModule } from ‘@angular/forms’;
import { AppComponent } from ‘./components/app/app.component’
import { NavMenuComponent } from ‘./components/navmenu/navmenu.component’;
import { HomeComponent } from ‘./components/home/home.component’;
import { UserComponent } from ‘./components/user/user.component’;
import { UserService } from ‘./components/service/user.service’;
import { BarCodePipe } from ‘./components/pipe/custom.pipe’;
export const sharedConfig: NgModule = {
bootstrap: [ AppComponent ],
declarations: [
AppComponent,
NavMenuComponent,
HomeComponent,
UserComponent,
BarCodePipe
],
imports: [
RouterModule.forRoot([
{ path: ”, redirectTo: ‘home’, pathMatch: ‘full’},
{ path: ‘home’, component: HomeComponent },
{ path: ‘user’, component: UserComponent }
{ path: ‘**’, redirectTo: ‘home’ }
])
],
providers: [UserService]
};

  • What is If-Else-and-Then Conditions in Angular4?

a. The “If” evaluates expression and then renders the “else” or “then” template in its place when expression is “truthy” or “falsy” respectively.

Then: – This template is the inline template of “If” unless bound to a different value.
Else: – This template is blank unless it is bound.

Selectors: –
If
If then
If else
The multiple examples for Angular 4 if else and then as given bellows,

Syntax:-

Syntax:-

{{user.Id}}

{{user.name}}

{{user.Age}}

loading…
Syntax :- We can also use ‘then else’

If IsValid then
display other

content here…
other content here…
Example 1 as,

Display valid content here …

 

Other content here…

Example 2 as,

Please login to continue.
Hi Anil!.
Example 3 as,
//our root app component
import {Component, NgModule} from ‘@angular/core’
import {BrowserModule} from ‘@angular/platform-browser’
@Component({
selector: ‘else-cmp’,
template: `

content here …

other content here…`,
})
export class ElseComponent {
isValid:boolean = true;
constructor() {
}
}
@Component({
selector: ‘else-then-cmp’,
template: `

content here…
other content here…
`,
})
export class ElseThenComponent {
isValid:boolean = true;
constructor() {
}
}
@Component({
selector: ‘my-app’,
template: `

Using else :

 

Using else then:

`,
})
export class App {
isValid:boolean = true;
constructor() {
}
}
@NgModule({
imports: [ BrowserModule ],
declarations: [ App , ElseComponent, ElseThenComponent],
bootstrap: [ App ]
})
export class AppModule {}

 

  • Explain component decorators in Angular4

a. A decorator is the core concept when developing an angular framework with version 2 and above. It may become a core language feature for JavaScript soon. In angular 4, decorators are used extensively and are also used to compile a code. There are 4 different types of decorators:

Class decorators
Property decorators
Method decorators
Parameter decorators

A decorator is a function that is invoked with a prefixed “@” symbol and is immediately followed by a class, parameter, method, or property. A decorator returns the same thing which was given as an input but in an augmented form.

Angular Interview Questions

  • Write the CLI command to generate a component in Angular4.

a. Components are just simple classes which are declared as components with the help of component decorators.

It becomes easy to create an application which already works, with the help of angular CLI commands. “Ng generate” is used to generate components, routes, services, and pipes. Simple test shells are also created with the help of this CLI command. For generating a component in angular4 with the help of CLI command, you need to follow the following syntax-
ng generate component component_name;
It generates the component and adds the component to module declarations.

  • Explain the component directory structure of angular4.

a. Here are the elements which are present in the component directory structure anf modules: –
module.ts- in this, the angular module is declared. @NgModule decorator is used which initializes the different aspects of angular applications. AppComponent is also declared in it.

components.ts- it simply defines the components in angular and this is the place where the app-root sector is also defined. A title attribute is also declared in the component.

component.html- it is the template file of the application which represents the visual parts of our components.

  • Explain ngFor directive with an example.

a. The ngFor directive instantiates a template for every element of the given iterator. The different local variables of the ngFor directive can be used in iterations. The ngFor directive can even be used with the HTML elements. It also performs various changes in DOM. Several exported values can be aliased to local variables with the help of ngFor directive. It allows us to build data presentation lists and tables in our HTML templates. Here’s an example of ngFor directive with the help of HTML:

    ({hero.name})

 

Angular Interview Questions

  • Explain property binding or one way binding in angular js

a.Basically, property binding means passing data from the component class and setting the value of a given element in the view. It is a one-way binding in which the data is passed from component to the class. It allows us to control the element property values from component to class. Property binding in angular can take place by three ways:
Interpolation can be used to define a value, as long as the value being defined is a string.
Wrapping brackets around the element property and binding it to the component property is the most common type of property binding.
The third way is by adding “bind” before the element property.

  • Explain ngIf directive with an example.

a.The ngIf is a built-in template directive which is used to add or remove some parts of DOM. This addition or removal depends on the expression being true or false.

If the expression is evaluated to false, then the ngIf directive removes the HTML element. If the expression is evaluated to be true, then the element gets added to the DOM.

Syntax- *ngIf=”” Example-

    *ngIf=”person.age < 30”>

  • {{person.name}}

 

  • Write the difference between directive and component in angular js

a.In angular js, there are differences between the meta-data annotations. Some of the differences are:

A directive is used to add behavior to an existing element. Whereas, a component is used to create a component with attached behavior.
“@directive” is used to create a directive. Whereas, “@component” is used to create a component.
A directive is used to attach different behaviors to an existing DOM element. Whereas, with the help of component, we can break our application into smaller components.
A directive is used to create reusable behavior. Whereas, a component is used to create reusable components.
A directive does not require a view. Whereas, a component needs a view via @view.

Angular Interview Questions

  • What do you understand by Isolated Unit Tests?

a.As the name implies, unit test is all about testing individual units of code. In order to answer some questions, isolating the unit of code under test is really important. When we do this, we are not forced into creating related pieces such as DOM elements for sorting. With the help of isolated unit tests, it becomes easier to implement everything. To simulate the requests, dependency injections are also provided. The individual sort function can be tested in isolation. And not only the sort function, any function can be tested in isolation.

  • What is a routing in angular js?

a.ngRoute module is used when you want to navigate through different pages of your application but you also want your application to be a single page application. This ngRoute module navigates through different pages of your application without reloading the entire application. The angular js route module should be included to make your application ready for routing. The ngRoute is added as a dependency in the application. The routing engine captures the specific url requested by the user and renders the view based on the defined routing rules.

Angular Interview Questions

  • What do you understand by services with reference to angular js?

a.Services in angular js are used to organize and share code across your application. These are the suitable objects which are wired together with the help of dependency injection. The angular js services are lazily instantiated. The service is only instantiated by angular js only when the application component depends on it. In angular js, new services can be made or can even be used in other built-in services. Over 30 built-in services are present in angular js.

  • What is TypeScript?

a.TypeScript is a superset of Javascript. So any valid Javascript code is also a TypeScript code. TypeScript has many additional features that Javascript doesn’t offer:

Strong Type – You can specify variable type at the time of declaring a variable which makes code easier to maintain and catching errors become easier. Although this feature is optional.
Object Oriented features – TypeScript brings many object oriented features which have been missing in Javascript like classes, interfaces, constructor, access modifier, properties etc.
In TypeScript, We can catch error at compile time instead of runtime
With TypeScript, We also get intellisense in the code editor.

 

Angular Interview Questions

  • Building blocks of Angular Apps

a.Components – Angular embraces component based architecture which allows us to work with smaller and maintainable piece of code that can be reused at several places. Each Angular App has one or more components. A component controls a patch of screen called a view. It encapsulates Data, HTML template and Logic for a view (area of the screen that the users see).

Every application has a root component that we call as App component.

Modules – It is container for group of related components, i.e. in an employee module, we can have components for displaying employees details. Every Angular app has at least one NgModule class, the root module, conventionally named AppModule.

Templates – You define a component’s view with its companion template. A template is a form of HTML that tells Angular how to render the component.

Metadata – Metadata tells Angular how to process a class.

Example

In fact, CourseListComponent really is just a class. It’s not a component until you tell Angular about it.

To tell Angular that CourseListComponent is a component, attach metadata to the class.

In TypeScript, you attach metadata by using a decorator. Here’s some metadata for CourseListComponent:
@Component({
selector: ‘app-course-list’,
templateUrl: ‘./course-list.component.html’,
providers: [ courseService ]
})

export class CourseListComponent implements OnInit {
/* . . . */
}

Directives – A directive is a class with a @Directive decorator. A component is a directive-with-a-template; a @Component decorator is actually a @Directive decorator extended with template-oriented features.

Directives either alter the layout structure (for example, ngSwitch) or modify aspects of DOM elements and components (for example, ngStyle and ngClass).

Of course, you can also write your own directives. Components such as HeroListComponent are one kind of custom directive.

Services – A service is typically a class with a narrow, well-defined purpose. Components are big consumers of services. Component classes should be lean. They don’t fetch data from the server, validate user input, or log directly to the console. They delegate such tasks to services. A component’s job is to enable the user experience and nothing more. It mediates between the view (rendered by the template) and the application logic.

Angular factor your application logic into services and make those services available to components through dependency injection.

Dependency injection is a way to supply a new instance of a class with the fully-formed dependencies it requires. Most dependencies are services. Angular uses dependency injection to provide new components with the services they need.

  • Steps to follow in order to use component

a.Create a Component
Register it in a module
Add an element in an HTML markup

Angular Interview Questions

KyrosAcademy

This information box about the author only appears if the author has biographical information. Otherwise there is not author box shown. Follow YOOtheme on Twitter or read the blog.
+91 9952948899 info@kyrosacademy.com

Offcanvas