Angular Interview Questions

Angular CLI

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 AngularJS 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)
Object − An object is a real time representation of any entity. According to Grady Brooch, every object must have three features −
  • State − described by the attributes of an object
  • Behavior − describes how the object will act
  • Identity − a unique value that distinguishes an object from a set of similar such objects.
Class − A class in terms of OOP is a blueprint for creating objects. A class encapsulates data for the object.

Method − Methods facilitate communication between objects.

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: Angularjs 2.0 framework has 9 main building blocks such as:
  • Metadata
  • Module
  • Component
  • Template
  • Data Binding
  • Event Binding
  • Directive
  • Service
  • Dependency Injection
Q: Briefly explain Angular 2 Metadata

Metadata in Angularjs 2:
In Angular2.0, 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 Angularjs 2
Both Angular 1.x and 2.0 apps are modular. However, in Angular2.0 NgModules  has been introduced as its modularity system. Every Angular2.0 must have one module which acts as the root module and conventionally named as AppModule. If the project has been created using angular-cli, AppModule is created in file src/app/app.module.ts.

However, there can be more than one module in a single Angular2.0 app.

@NgModule decorators pass a metadata, with properties such as declaration, imports, providers, export and bootstrap in order to create the module class.
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 { routedComponents, AppRoutingModule } 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 { }

Q: Development Angularjs 2.0 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: How Can We Setting Up Our Development Environment For Angular 2?
Setting up our development environment for Angular 2 requires two basic steps:
  1. Install npm, or node package manager.
  2. Set up the Angular 2 application.
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 4? What is the use of a 'polyfill.ts' file in Angular 4?
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: How Can We Setting Up Angular 2 Application?
  1. Create an application folder.
  2. Create the tsconfig file(To configure the TypeScript compiler).
  3. Create the package.json file(To define the libraries and scripts we need).
  4. Create the typings.json file(That specifies a missing TypeScript type definition file).
  5. Install the libraries and typing files.
  6. Create the host Web page.(Normally index.html).
  7. Create the main.ts file(To bootstrap the Angular application with the root component).
Q: Explain the life cycle hooks of Angular 2 application

Angular 2 component/directive has lifecycle events, managed by @angular/core. It creates the component, renders it, creates and renders its children, processes changes when its data-bound properties change, and then destroys it before removing its template from the DOM. Angular provides a set of lifecycle hooks(special events) which can be tapped into this lifecycle and perform operations when required. The constructor executes prior to all lifecycle events. Each interface has a single hook method prefixed with ng. For example, ngOnint interface has Oninit method that must be implemented in the component.

Some of the events are applicable for both component/directives while few are specific to components.

  1. ngOnChanges: Responds when angular sets its data-bound property which receives the current and previous object values.
  2. ngOnInit: Initializes the component/directive after first ngOnChange triggers. This is most frequently used method to retrieve the data for the template from a back-end service.
  3. ngDoCheck: Detect and act upon changes occuring outside Angular context. It is called when every change detection run.
  4. ngOnDestroy: Cleanup just before Angular destroys the directive/component. Unsubscribe observables and detach event handlers to avoid memory leaks.

Component-specific Hooks:

  1. ngAfterContentInit: Component content has been initialized
  2. ngAfterContentChecked: After Angular checks the bindings of the external content that it projected     into its view.
  3. ngAfterViewInit: After Angular creates the component’s view.
  4. ngAfterViewChecked: After Angular checks the bindings of the component’s view.

Q: What are the new features of Angular2?
Angular 2 is written entirely in Typescript and meets the ECMAScript 6 specification.

  1. Component-Based- Angular 2 is entirely component based. Controllers and $scope are no longer used. They have been replaced by components and directives.
  2. Directives- The specification for directives is considerably simplified, although they are still subject to change. With the @Directive annotation, a directive can be declared.
  3. Dependency Injection- Because of the improved dependency injection model in Angular2 there are more opportunities for component / object-based work.
  4. Use of TypeScript-TypeScript is a typed super set of JavaScript which has been built and maintained by Microsoft and chosen by the AngularJS team for development. The presence of types makes the code written in TypeScript less prone to run-time errors. In recent times, the support for ES6 has been greatly improved and a few features from ES7 have been added as well.
  5. Generics- TypeScript has generics which can be used in the frontend.
  6. Lambdas with TypeScript- In TypeScript, lambdas are available.
  7. Forms and Validations- Forms and validations are an important aspect of frontend development. Within Angular 2 the Form Builder and Control Group are defined.
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 2 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 Angular 2 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 is @NgModule?
@NgModule is a decorator function. A decorator function allows users to mark something as Angular 2 thing (could be a module or component or something else) and it enables you to provide additional data that determines how this Angular 2 thing will be processed, instantiated and used at the runtime. So, whenever user writes @NgModule, it tells the Angular 2 module, what’s going to be included and used in and using this module.


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 templateurl 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 2+ 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 2.?

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 2 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 2?

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

    for( var i = 0; i < arr.length; i++ ) {
        // i IS known here
    }

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

    for( let j = 0; j < arr.length; j++ ) {
        // 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.

Tuples  represents a heterogeneous collection of values. In other words, tuples enable storing multiple fields of different types. Tuples can also be passed as parameters to functions.

Syntax
var tuple_name = [value1,value2,value3,…value n]

For Example
var mytuple = [10,"Hello"];
You can also declare an empty tuple in Typescript and choose to initialize it later.
var mytuple = []; 
mytuple[0] = 120 
mytuple[1] = 234
Example: Simple Tuple
var mytuple = [10,"Hello"]; //create a  tuple 
console.log(mytuple[0]) 
console.log(mytuple[1])

Interfaces
Interfaces define properties, methods, and events, which are the members of the interface. Interfaces contain only the declaration of the members.

Example: Interface and Objects
interface IPerson { 
   firstName:string, 
   lastName:string, 
   sayHi: ()=>string 
} 

var customer:IPerson = { 
   firstName:"Tom",
   lastName:"Hanks", 
   sayHi: ():string =>{return "Hi there"} 
} 

console.log("Customer Object ") 
console.log(customer.firstName) 
console.log(customer.lastName) 
console.log(customer.sayHi())  

var employee:IPerson = { 
   firstName:"Jim",
   lastName:"Blakes", 
   sayHi: ():string =>{return "Hello!!!"} 
} 
  
console.log("Employee  Object ") 
console.log(employee.firstName) console.log(employee.lastName)

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-
Routes describes the application’s routes
RouterOutlet is a “placeholder” component that gets expanded to each route’s content
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 are pipes in Angular 2 ?
Pipes in Angular 2 are a way to transform and format data right from your templates Out of the box you get pipes for dates, currency, percentage and character cases, but you can also easily define custom pipes of your own.

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 splitted into various child modules (NgModule) based on the application business case.

Q: Briefly explain Event Binding in Angular 2?

Event Binding in Angularjs 2:

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 sytax 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 HTML5. Such as
 
<div (mousedown)="eventName($event)"></button>
 
And then in component
 
@Component(...)
class AppComponent {
  eventName(event) {
    event.preventDefault();
  }
}
Q: Advantages of using Angular 2 over Angular 1?
  1. Angular 2 is a platform not only a language:
  2. Better Speed and Performance: No $Scope in Angular 2, AOT
  3. Simpler Dependency Injection
  4. Modular, cross platform
  5. Benefits of ES6 and Typescript.
  6. Flexible Routing with Lazy Loading Features
  7. Easier to Learn
Q: Angular4 vs. Angular2
  • Angular 4 is faster than Angular 2. The apps developed in Angular 4 are five times faster and smaller as compared to Angular 2.
  • TypeScript 2.1 and 2.2 compatiblity. Before Angular 4, only TypeScript 1.8 was supported. So with Angular 4, we have all new features of Typescript available.
  • We can now use new if/else style syntax with *ngif structural directive. In Angular 2, it was not possible to use "else" statement with nglf, but now it has been made possible in Angular 4.
  • Angular 4 has introduced a new titlecase pipe. It changes the first letter of each word into uppercase
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 IS THE USE OF INTERCEPTORS IN ANGULAR 4?
The Interceptors is a common used to set default headers for all responses.

Q: What Are The Core Differences Between Observables And Promises?
The major difference between Promises and Observables is that Observables are a set of values, zero to an infinite number of values, where Promises are only one value.

Observables can be synchronized and Promises are always asynchronized. So there’s a variety of differences. Also, Observables can be canceled and Promises cannot be canceled.

Promises vs Observables :

Promises:
returns a single value.
not cancellable.

Observables:
works with multiple values over time.
cancellable.
supports map, filter, reduce and similar operators.
proposed feature for ES 2016.
use Reactive Extensions (RxJS).
an array whose items arrive asynchronously over time.

Q: What is Webpack?
webpack is a module bundler. Its main purpose is to bundle JavaScript files for usage in a browser, yet it is also capable of transforming, bundling, or packaging just about any resource or asset. https://github.com/

Install with npm:
npm install --save-dev webpack

Q: HOW ARE JWTS USED TO AUTHENTICATE ANGULAR 4 APPLICATIONS?
In Annular, the following Steps are used to building authentication and authorization for RESTful APIs and applications. It might help you –

  1. The users send their credentials to the server which is verified by the database credentials. If everything is verified successfully, the JWT is sent back to them.
  2. The JWT is saved in the user’s browser in local storage or in a cookie and so on.
  3. The presence of a JWT saved in the browser is used as an indicator that a user is currently logged in.
  4. The expiry time of JWT is continually checked to maintain an authenticated state in the Angular applications.
  5. The client side routes are protected and access by authenticated users only.
  6. When user sends the XHR requests for APIs, the JWT gets sent an Authorization header using your cookies or Bearer.
  7. When XHR requests coming on the server, before send back the responses it’s validated first with configured app’s secret keys. If everything is looking good then returns successfully responses other send the back to the bad request.
  8. There are several open source libraries are available for angular which are helps with JWTs and has the ability to Decode the JWT, Authorization header to XHR requests and so on.

Q: What’s new in Angular 5?
Certain tools are optimized in the new version of Angular, let us see what the tools are:

  • Angular 5 supports Typescript version 2.4
  • Angular 5 supports RxJS 5.5 which has new features like Pipeable Operators
  • A build tool to make the js bundles (files) lighter
  • Ahead of Time (AOT) is updated to be on by default
  • Events like ActivationStart and ActivationEnd are introduced in Router

Q: What is the use of @Input and @Output? 
When it comes to the communication of Angular Components, which are in Parent-Child Relationship; we use @Input in Child Component when we are passing data from Parent to Child Component and @Output is used in Child Component to receive an event from Child to Parent Component.

Q: What is ng-content Directive? 
The HTML elements like p (paragraph) or h1 (heading) have some content between the tags. For example, <p>this is a paragraph</p> and <h1>this is a heading</h1>. Now, similar to this, what if we want to have some custom text or content between the angular tags like  <app-tax>some tax-related content</app-tax> This will not work the way it worked for HTML elements.  Now, in such cases, the <ng-content> tag directive is used.

Q: What does a router.navigate do?
When we want to route to a component we use router.navigate.  Syntax: this.router.navigate([‘/component_name’]);

Q:What is Redux? 
It is a library which helps us maintain the state of the application. Redux is not required in applications that are simple with the simple data flow, it is used in Single Page Applications that have complex data flow.

Q: What is JSONP Data type?
JSONP, which stands for "JSON with Padding" (and JSON stands for JavaScript Object Notation), is a way to get data from another domain that bypasses CORS (Cross Origin Resource Sharing) rules.

Q: What is CORS?
CORS is a set of "rules," about transferring data between sites that have a different domain name from the client.

Q: What is the difference between *ngIf vs [hidden]?
*ngIf effectively removes its content from the DOM while [hidden] modifies the display property and only instructs the browser to not show the content but the DOM still contains it.

Q: How would you protect a component being activated through the router?
The Angular router ships with a feature called guards. These provide us with ways to control the flow of our application. We can stop a user from visitng certain routes, stop a user from leaving routes, and more. The overall process for protecting Angular routes:
  • Create a guard service: ng g guard auth
  • Create canActivate() or canActivateChild() methods
  • Use the guard when defining routes
// import the newly created AuthGuard
const routes: Routes = [
  {
    path: 'account',
    canActivate: [AuthGuard]
  }
];
Some other available guards:
  1. CanActivate: Check if a user has access
  2. CanActivateChild: Check if a user has access to any of the child routes
  3. CanDeactivate: Can a user leave a page? For example, they haven't finished editing a post
  4. Resolve: Grab data before the route is instantiated
  5. CanLoad: Check to see if we can load the routes assets
Q: How would you run unit test?
The Angular CLI downloads and install everything you need to test an Angular application with the Jasmine test framework.
The project you create with the CLI is immediately ready to test. Just run this one CLI command:

ng test

Q: How to bundle an Angular app for production?
Q: How to inject base href?
Q: What is Redux and how does it relate to an Angular app?
Q: How to set headers for every request in Angular?

What does a Subscribe method do in Angular 4? 
It is a method which is subscribed to an observable. Whenever the subscribe method is called, an independent execution of the observable happens.

What is an AsyncPipe in Angular? 
We use the async pipe to automatically subscribe/unsubscribe to our observable.

<ul class="user__list" *ngIf="(users$ | async).length">
    <li class="user" *ngFor="let user of users$ | async">
        {{ user.name }} - {{ user.birth_date }}
    </li>
</ul>

Please note the dollar sign. Using the dollar sign in the name of a variable that is an observable, is considered best practice. This way it’s easy to identify if your variable is an observable or not.




For More Questions follow another helpfull link Click here

2 comments:


  1. Pretty blog, so many ideas in a single site, thanks for the informative article, keep updating more article.
    Webdesining course in chennai

    ReplyDelete

Topics

ADO .Net (2) Ajax (1) Angular Js (17) Angular2 (24) ASP .Net (14) Azure (1) Breeze.js (1) C# (49) CloudComputing (1) CMS (1) CSS (2) Design_Pattern (3) DI (3) Dotnet (21) Entity Framework (3) ExpressJS (4) Html (3) IIS (1) Javascript (6) Jquery (9) Lamda (3) Linq (11) Mongodb (1) MVC (48) NodeJS (7) RDLC (1) Report (1) Sql Server (29) SSIS (3) SSRS (2) UI (1) WCF (12) Web Api (10) Web Service (1) XMl (1)