Angular Interview Questions


What Is Angular?
Angular is an open-source, front-end web development framework based on TypeScript. It is most suited for developing enterprise web applications because the code is reusable and maintainable.

What is SPA in Angular?
Angular is a Single Page Applications Framework. Single page application (SPA) is a web application that fits on a single page. All your code (JavaScript, HTML, CSS) is retrieved with a single page load. And navigation between pages performed without refreshing the whole page.

Why We should choose Angular?
Angular is a architectural solution for creating SPA application using JavaScript framework. It provides built In features like Module, Component, Directives, Pipes, HTTP Services, Routing, Rxjs support and many more.

Angular CLI
Angular CLI is a tool that help us create angular applications, components, modules, pipes, directives, services and much more with great speed and consistency

Angular CLI stands for Command-line Interface.
  • CLI provides ng new, ng serve, ng build, ng test Commands
  • CLI compiles TypeScript to JavaScript
  • CLI uses Nodejs in the background for Angular Compilation
Q: What is ECMA Script ?
ECMAScript is a standard for modern scripting-language specification. Initially, it was JavaScript, now its being changing to ECMAScript.

TypeScript
TypeScript is a typed super set of JavaScript which has been built and maintained by Microsoft and chosen by the Angular team for development.
TypeScript is Object-Oriented JavaScript. Object Orientation is a software development paradigm that follows real-world modelling. Object Orientation considers a program as a collection of objects that communicate with each other via mechanism called methods. TypeScript supports these object oriented components too.
var message:string = "Hello World" 
console.log(message)
Example: TypeScript and Object Orientation

class Greeting { 
    greet():void { 
       console.log("Hello World!!!"
    } 
 } 
 var obj = new Greeting(); 
 obj.greet();
 

The any data type is the super type of all types in TypeScript. It denotes a dynamic type. Using the any type is equivalent to opting out of type checking for a variable.

Q: Angular framework has 9 main building blocks such as:
  • Metadata
  • Module
  • Component
  • Template
  • Data Binding
  • Event Binding
  • Directive
  • Service
  • Dependency Injection
Q: Types of directives in Angular.
There are three types of directives – attribute, component, structural.

Q: How does an Angular application work?

Every Angular app consists of a file named angular.json. This file will contain all the configurations of the app.

"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"
      ]
    }
  }

Inside the build section, the main property of the options object defines the entry point of the application which in this case is main.ts.
The main.ts file creates a browser environment for the application to run, and, along with this, it also 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 { }

As one can see in the above file, AppComponent is getting bootstrapped.
This component 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:
1. Selector - used for accessing the component
2. Template/TemplateURL - contains HTML of the component
3. StylesURL - contains component-specific stylesheets

After this, 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.
This is how the index.html file looks:

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Angular</title>
  <base href="/">
  <meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
  <app-root></app-root>
</body>
</html>

The HTML template of the root component is displayed inside the <app-root> tags.

This is how every angular application works.

Q: Explain string interpolation and property binding in Angular.
Data-binding can be done in two ways, one-way binding and two-way binding.
In Angular, data from the component can be inserted inside the HTML template. In one-way binding, any changes in the component will directly reflect inside the HTML template but, vice-versa is not possible. Whereas, it is possible in two-way binding.

String interpolation and property binding allow only one-way data binding.
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, {{ 2 + 2 }} will be evaluated by Angular and the output 4, will be displayed inside the HTML template. Using property binding, we can bind the DOM properties of an HTML element to a component's property. Property binding uses the square brackets [ ] syntax.

Q: What is the difference between Interpolation and Property binding
  • Interpolation is a special syntax that Angular converts into a property binding. 
  • Interpolation is just a convenient alternative to property binding. 
  • In some cases like when we need to concatenate strings we have to use interpolation instead of property binding as shown in the example below. 
<img src='http://www.pragimtech.com/{{imagePath}}' />

Q: Briefly explain Angular Metadata
Metadata are used with the class decorators in Angular. different decorators are used to pass variables to class. Such as @NgModules decorator is used for Modules. @Component decorator is used to pass variables to class. Decorators uses metadata to attach variable to component or module class.

@NgModule({
    declarations: [
      AppComponent
    ],
    imports: [
      BrowserModule,
      FormsModule,
      HttpModule
    ],
    providers: [],
    exports:[
        AppComponent
    ],
    bootstrap: [AppComponent]
  })

Here @NgModule pass a metadata, which is kind of json variable with properties such as declaration, imports, providers, export and bootstrap.
Similarly, @Component decorator also used metadata.

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
  })

In brief, metadata defines the properties for any module or component. Metadata helps any class to process and execute.

Q: Module in Angular
Module divides your application into small, reusable and functional component. it is a place where we can group components, directives, services, and pipes. Module decides whether the components, directives, etc. can be used by other modules, by exporting or hiding these elements. Every module is defined with a @NgModule decorator.
By default, modules are of two types:
  • Root Module
  • Feature Module
Every application can have only one root module whereas, it can have one or more feature modules.
A root module imports BrowserModule, whereas a feature module imports CommonModule.

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpModule } from '@angular/http';
import { FormsModule } from '@angular/forms';

import { AppComponent } from './app.component';
import { routedComponentsAppRoutingModule } from './app.routing';
import { UserService } from './services/user.service';

@NgModule({
  declarations: [
    AppComponent,
    routedComponents
  ],
  imports: [
    BrowserModule,
    HttpModule,
    FormsModule,
    AppRoutingModule
  ],
  providers: [UserService],
  bootstrap: [AppComponent]
})
export class AppModule { }

Creating Module:  ng g m test-module

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';

@NgModule({
  declarations: [],
  imports: [
    CommonModule
  ]
})
export class TestModuleModule { }

Q: What is Angular Services?
Services are objects which get instantiated only once during the lifetime of an application. The main objective of a service is to share data, functions with different components of an Angular application.
A service is defined using a @Injectable decorator. A function defined inside a service can be invoked from any component or directive.
To create a service, run the following command:
ng g s test-service

import { Injectable } from '@angular/core';
@Injectable({
  providedIn: 'root'
})
export class TestServiceService {
  constructor() { }
}

Any method/function defined inside the TestServiceService class can be directly used inside any component by just importing the service.

Q: Development Angular Application Using ANGULAR-CLI:

Pre-requirement:

Install latest Node.js
Download NodeJs 7.0 + version from https://nodejs.org/en/

Install NodeJs
Check if Nodejs installation is correct by running the command from command prompt
‘npm -version’
Install angular-cli (https://cli.angular.io/)
Install angular-cli by following commandInstall Angular CLI
npm install -g angular-cli
The next step is to create the application from command line.

Q: ng help  Command
above command will list all the available commands and their description.

Q: ng version -
above command check cli installed or not.
Q: What Is Npm?
Npm, or node package manager: is a command line utility that interacts with a repository of open source projects, Become the package manager for JavaScript. Using npm we can install libraries, packages, and applications, along with their dependencies.

Q: What is 'polyfills' in Angular ? What is the use of a 'polyfill.ts' file in Angular?
Polyfills in basic language are extra lines of code which make your application compatible for different browsers. The code we write is mostly in ES6 and is not compatible with IE or Firefox and needs some environment setups before being able to be viewed or used in these browsers.

Q: Anular Packages: 

rxjs
Reactive Extensions Library for JavaScript, which includes methods for transforming, composing, and querying streams of data. It is utilized by several parts of the Angular framework, such as the HTTP and Forms modules.

zone.js
Angular relies on zone.js to run Angular's change detection processes when native JavaScript operations raise events.
Q: Explain the life cycle hooks of Angular 2 application
      Life cycle hooks

Q: Difference Between Constructor And NgOnInit?

Differences - Constructor Vs. ngOnInit

Angular 2 Constructors:-
The constructor is a default method runs when component is being constructed.
The constructor is a typescript feature and it is used only for a class instantiations and nothing to do with Angular 2.
The constructor called first time before the ngOnInit().

Angular 2 ngOnInit:-
The ngOnInit event is an Angular life-cycle event method that is called after the first ngOnChanges and the ngOnInit method is use to parameters defined with @Input otherwise the constructor is OK.
The ngOnInit is called after the constructor and ngOnInit is called after the first ngOnChanges.
The ngOnChanges is called when an input or output binding value changes.

Q: What Is An Component?

Each component is comprised of a template, which is the HTML for the user interface. Add to that a class for the code associated with a view. The class contains the properties and methods, which perform actions for the view, A component also has metadata, which provides additional information about the component to Angular.

Q: What Are Differences Between Components And Directives?

Components : 
For register component we use @Component meta-data annotation.
Component is a directive which use shadow DOM to create encapsulate visual behavior called components. Components are typically used to create UI widgets.
Component is used to break up the application into smaller components.
Only one component can be present per DOM element.
@View decorator or template URL template are mandatory in the component.

Directives : 
For register directives we use @Directive meta-data annotation.
Directives is used to add behavior to an existing DOM element.
Directive is use to design re-usable components.
Many directive can be used in a per DOM element.
Directive don’t have View.

Q: Role of imports / exports in Angular ngModule
import: It enables an Angular module to use functionality that was defined in another Angular module.

export: It enables an Angular module to expose some of its components/directives/pipes to the other modules in the applications. Without it, the components/directives/pipes defined in a module could only be used in that module.

Q: How Routing Works In Angular?

Routing is a mechanism which enables user to navigate between views/components. Angular 2 simplifies the routing and provide flexibility to configure and define at module level (Lazy loading).

The angular application has single instance of the Router service and whenever URL changes, corresponding Route is matched from the routing configuration array. On successful match, it applies redirects and the router builds a tree of ActivatedRoute objects and contains the current state of the router. Before redirection, the router will check whether new state is permitted by running guards (CanActivate). Route Guards is simply an interface method that router runs to check the route authorization. After guard runs, it will resolve the route data and activate the router state by instantiation the required components into <router-outlet> </router-outlet>.

Q: What is Angular Guards?
There are four different guard types available, and we can use them to protect application routes before they navigate,
  • CanActivate : It decides if a route can be activated or not
  • CanActivateChild : it decides if child routes of a route can be activated or not
  • CanDeactivate : It decides if a route can be deactivated or not
  • CanLoad : It decides if a module can be loaded lazily or not
Q: What Are Event Emitters And How It Works In Angular?
Angular 2 doesn’t have bi-directional digest cycle, unlike angular 1. In angular 2, any change occurred in the component always gets propagated from the current component to all its children in hierarchy. If the change from one component needs to be reflected to any of its parent component in hierarchy, we can emit the event by using Event Emitter api.

In short, EventEmitter is class defined in @angular/core module which can be used by components and directives to emit custom events.

@output() somethingChanged = new EventEmitter();

We use somethingChanged.emit(value) method to emit the event. This is usually done in setter when the value is being changed in the class.

This event emit can be subscribed by any component of the module by using subscribe method.

myObj.somethingChanged.subscribe(val=> this.myLocalMethod(val));

Q: What's the difference between let and var?
A variable defined using a var statement is known throughout the function it is defined in, from the moment it is defined onward.
A variable defined using a let statement is only known in the block it is defined in, from the moment it is defined onward.
To understand the difference, consider the following code:

function loop(arr) {
    // i IS NOT known here
    // j IS NOT known here

    forvar i = 0i < arr.lengthi++ ) {
        // i IS known here
    }

    // i IS known here
    // j IS NOT known here

    forlet j = 0j < arr.lengthj++ ) {
        // j IS known here
    }

    // i IS known here
    // j IS NOT known here
}

Here, we can see that our variable j is only known in the first for loop, but not before and after. Yet, our variable i is known in the entire function from the moment it is defined onward.
Built-in types: Number, String, Boolean, void, Null, Undefined
Null and undefined ─ Are they the same?
The null and the undefined datatypes are often a source of confusion. The null and undefined cannot be used to reference the data type of a variable. They can only be assigned as values to a variable.

However, null and undefined are not the same. A variable initialized with undefined means that the variable has no value or object assigned to it while null means that the variable has been set to an object whose value is undefined.

Q: Which components are used to configure routing in Angular 2?

There are three main components that we use to configure routing in Angular 2-
  1. Routes describes the application’s routes
  2. RouterOutlet is a “placeholder” component that gets expanded to each route’s content
  3. RouterLink is used to link to routes
Q: What is Traceur compiler ?
Traceur compiler compiles ECMAScript Edition 6 (ES6) (including classes, generators and so on) code on the fly to regular Javascript (ECMAScript Edition 5 [ES5]) to make it compatible for the browser.

Q: Why are decorators used in Angular 2 ?
In Angular 2, decorators allow developers to configure classes as particular elements by setting metadata on them. The most commons are the @Component one, for components and the @Injectable one, for classes you want to inject dependencies in.

Advanatges of using decorators are-
Separation of concerns.
Easy for tools to provide all kinds of support in templates like- error checking, auto-completion, graphical GUI designers
Support multiple modifications

Q: What is lazy loading and How to enable lazy loading in angular 2?
Lazy lading enables us to load only the module user is interacting and keep the rest to be loaded at runtime on demand.
Lazy loading speeds up the application initial load time by splitting the code into multiple bundles and loading them on demand.
Every Angular application must have one main module say AppModule. The code should be splited into various child modules (NgModule) based on the application business case.

Q: Briefly explain Event Binding in Angular 2?

Event Binding in Angular:

Angular 2 has been developed to be more synchronized with modern HTML5. Therefore, events has been changed to bind to the DOM API Events with similar syntax.

For example, ng-click has been replaced with (click). Same as ng-submit has been changed to  (submit). () parenthesis has been used as the syntax for event emitter.

//Angularjs 1.x
<div ng-click="eventName()"></div>
//Angular 2.0
<div (click)="eventName()"></div>
 
Respective event object can also be passed as HTML5Such as
 
<div (mousedown)="eventName($event)"></button>
 
And then in component
 
@Component(...)
class AppComponent {
  eventName(event) {
    event.preventDefault();
  }
}

Q: What Are ngIf and ngFor? 
Just like if and for in other languages, ngIf and ngFor are used as control statements. 

Example
<p *ngIf="display">Show this only if the Boolean "display" is true</p>
Where the display is a boolean with the value true or false. 

ngFor is used to loop through and display elements of an array (set of data).
<tr *ngFor="let student of students; let i = index"> <td>{{student.name}}
</td> <td>{{i}}</td> </tr>

The second part (i=index) is optional and only needed if you want to display the index.

Q: What is Data binding?
Data Binding is the process of connecting information with displayable objects from a programmatic perspective.

One-Way Data Binding
One-way data binding is a situation where information flows in only one direction, typically from a data source to the control. This has the effect of making the variable read-only from the user's perspective. Anything they do with the control won't affect the information it displays. 

Two-Way Data Binding
Two-way data binding is when information flows in both directions, from data source to the control, and from the control to data source. This has the effect of allowing the variable to be updated by the user. Anything they do with the control will affect the information it displays and the information that gets stored. 

Q: What Does the Representation [()] Mean?
This is a representation for ngModel used for two-way data binding. It is written as [(ngModel)] = “property value”.

Q: What Are the Various Filters/Pipe Supported by Angular?
Filter nameDescription
UppercaseConvert string to uppercase
LowercaseConvert string to lowercase
DateConvert date to the specified format
CurrencyConvert the number to currency format
NumberFormat number into a string
OrderbyOrders an array by specific expression
limitToLimits array into the specified number of elements; string to specified number of characters
JSONFormat object to JSON string
FilterA select a subset of items from the array
You can mention few of them and show an example as well –
<p>Amount: {{ amount | currency }}</p>
Q: Explain ngFor directive with an example.
<tr *ngFor="hero of heroes">
<td>({hero.name})</td>
</tr>

Q: Explain ngIf directive with an example.
<ul *ngFor="let person of people" *ngIf="person.age < 30">
    <li>{{person.name}}</li>
</ul>

Q: Using which wild card we can define page not found route
     **

Q: There can be more than one <router-outlet> element in angular application
    True

Q: Below service can be used to extract route parameters inside component
ActivatedRoute

Q: In Angular, you can pass data from parent component to child component using
    @Input()

Q: In Angular, you can pass data from child component to parent component using
    @Output()

Q: What Are The Core Differences Between Observables And Promises?
      Click here

Q: Observable retry on error
       to resubscribe and retry an Observable if there is an error we can use below operator. Click here

// Retry only 3 times if there is an error
.retry(3)

// Retry with a delay of 1000 milliseconds (i.e 1 second)
.retryWhen((err) =] err.delay(1000))

this._employeeService.getEmployeeByCode(empCode)
// Retry 5 times maximum with a delay of 1 second 
// between each retry attempt
.retryWhen((err) =] {
    return err.scan((retryCount, val) =] {
        retryCount += 1;
        if (retryCount 6) {
            this.statusMessage = 'Retrying...Attempt #' + retryCount;
            return retryCount;
        }
        else {
            throw (err);
        }
    }, 0).delay(1000)
})

Q: What Is the ng-template?
ng-template is the directive that contains some html contents with an Id(#id). ng-template is shown based on condition(*ngif) in Angular.

<div>
   <span *ngIf = "isavailable;then condition1 else condition2">Condition is valid.</span>
   <ng-template #condition1>Condition is valid from template</ng-template>
   <ng-template #condition2>Condition is invalid from template</ng-template>
</div>

If the condition is true, then the condition1 template is called, otherwise condition2.

Q: zip operator in rxjs
Zip operator is used to combine emission from multiple observable into a single observable.
Zip Operator Works in Sequence. That means each observable will be executed sequentially.
 This method is useful if you have to make several HTTP requests at the same time in a component, and you need to wait for all requests to be completed before emitting the values.
 

1 comment:

Topics

ADFS (1) ADO .Net (1) Ajax (1) Angular (43) Angular Js (15) ASP .Net (14) Authentication (4) Azure (3) Breeze.js (1) C# (47) CD (1) CI (2) CloudComputing (2) Coding (7) CQRS (1) CSS (2) Design_Pattern (6) DevOps (4) DI (3) Dotnet (8) DotnetCore (16) Entity Framework (2) ExpressJS (4) Html (4) IIS (1) Javascript (17) Jquery (8) Lamda (3) Linq (11) microservice (3) Mongodb (1) MVC (46) NodeJS (8) React (11) SDLC (1) Sql Server (32) SSIS (3) SSO (1) TypeScript (1) UI (1) UnitTest (1) WCF (14) Web Api (15) Web Service (1) XMl (1)

Dotnet Guru Archives