Monday, 3 July 2017

Angular 2 interview questions

1. What is Angular 2? 13 Best Advantages for Angular 2!

Angular 2 is a most popular framework for developing mobile apps.  It is also for “desktop” as well “mobile” applications.  The Angular 2 is development phase you know very well and hopefully you love.

The “Angular 2” is focusing on data-binding, extensible HTML and on application test-ability.

Angular framework helps us to build client applications in HTML and JavaScript.
Angular 2 is so simpler, faster, modular and instrumented design.

Angular 2 targeting to modern browsers and it is developing using ES6 (ES6 is called ECMAScript version 6). It also support to ECMAScript version 5(ES5).

You don’t worry about the versions of ECMAScript. The ES6 compiler manages to the versioning related problems.

All the Angular 2 framework code is already being written in ECMAScript 6.
The set of modern browsers are
1.              Chrome
2.              Firefox
3.              Opera
4.              Safari
5.              IE Version10, 11 and so on...

On mobiles, it is supporting to the list of Chrome on Android, iOS 6+, Windows Phone 8+ and Fire-Fox mobile and also trying to support to older versions of Android.

Angular 2 team working with Traceur compiler team to provide the support to build some extensions. This set of extensions called “ES 6 +A”.

The “Angular 2” is using “Traceur” compiler. Traceur is a compiler that takes “ES6” and compiles it down (ES5) to regular JavaScript that runs in your browsers. It is run everywhere you want to do.



2. What is Traceur compiler?
The “Traceur” is a JavaScript compiler. The Traceur compiler is very popular now days use to allow use to use the features from the future. This compiler is fully supported to ES5, ES6 and also to vNext.

The main goal of Traceur compiler is to inform to design of new JavaScript features and wrote the programming code of new efficient and good manners.

3. What is Advantages of Angular 2?
1.       There is many more advantage of Angular 2.
2.       The Angular 2 has better performance.
3.       The Angular 2 has more powerful template system.
4.       The Angular 2 provide simpler APIs, lazy loading and easier to application debugging.
5.       The Angular 2 much more testable.
6.       The Angular 2 provides to nested level components.
7.       The Angular 2 execute run more than two programs at the same time.

The Angular 2 architecture diagram identifies the eight main building blocks as.

1.       Module
2.       Component
3.       Template
4.       Outpouts
5.       Data Binding
6.       Directive
7.       Service
8.       Dependency Injection

3. What Are The New Features Of Angular 2? Why You Used Angular 2?
Angular 2 Features –
·       Angular 2 is Entirely Component Based
·       Directives
·       Dependency Injection
·       Used of TypeScript
·       Used of Lambdas or Arrow functions
·       Generics
·       Forms and Validations
·       And So on..

Component Based- It is entirely component based. It is not used to scope and controllers and Angular 2 are fully replaced by components and directives.

Directives- The directive can be declared as @Directive annotation.
A component is a directive with a template and the @Component decorator is actually a @Directive decorator extended with template oriented features.

Dependency Injection- Dependency Injection is a powerful pattern for managing code dependencies. There are more opportunities for component and object based to improve the dependency injection.

Use of TypeScript- Type represents the different types of values which are using in the programming languages and it checks the validity of the supplied values before they are manipulated by your programs.

Generics- TypeScript has generics which can be used in the front-end development.

Lambdas and Arrow functions – In the TypeScript, lambdas/ arrow functions are available. The arrow function is additional feature in typescript and it is also known as a lambda function.

Forms and Validations- Angular 2 forms and validations are an important aspect of front-end development.


4. Why You Used Angular 2?
1.     It is entirely component based.
2.     Better change detection
3.     Angular2 has better performance.
4.     Angular2 has more powerful template system.
5.     Angular2 provide simpler APIs, lazy loading and easier to application debugging.
6.     Angular2 much more testable
7.     Angular2 provides to nested level components.
8.     Ahead of Time compilation (AOT) improves rendering speed
9.     Angular2 execute run more than two programs at the same time.
10.  Angular1 is controllers and $scope based but Angular2 is component based.
11.  The Angular2 structural directives syntax is changed like ng-repeat is replaced with *ngFor etc.
12.  In Angular2, local variables are defined using prefix (#) hash. You can see the below *ngFor loop Example.
13.  TypeScript can be used for developing Angular 2 applications

14.  Better syntax and application structure



5. What is AOT compilation? Why Use in Angular 2?
AOT compilation stands for “Ahead of Time compilation” and it are used to compiles the angular components and templates to native JavaScript and HTML during the build time instead of run-time.
The compiled HTML and JavaScript are deployed to the web server so that the compilation and render time can be saved by the browser. It is the big advantage to improve the performance of applications.

Advantages of AOT -
1.         Faster download: - The Angular 2 app is already compiled so it is faster.
2.         Faster Rendering: - If the app is not AOT compiled and the compilation process happens in the browser once the application is fully loaded. This has a wait time for all necessary components to be downloaded and then the time taken by the compiler to compile the app. With AOT compilation, this is optimized.
3.         Lesser Http Requests: - It is supporting to the lazy loading. Actually, lazy loading is great concepts for sending HTTP request to the server. It is minimise the multiple requests for each associated html and css, there is a separate request goes to the server.
4.         Detect error at build time: - In Angular 2, the compilation happens beforehand and most of the errors can be detected at the compile time and this process providing us a better application’s stability.

Disadvantages of AOT -
1.         AOT only works only with HTML and CSS and not for other file types. If required other file types that time we will need to follow the previous build step.
2.         We need to maintain AOT version of bootstrap file.

3.         We need to clean-up step before compiling.

6. What is lazy loading and How to enable lazy loading in angular 2?
Lazy Loading - Lazy loading enables us to load only the module user is interacting and keep the rest to be loaded at run-time on demand.

Lazy loading speeds up the application initial load time by splitting the code into multiple bundles and loading them on demand.

1.         Each and every Angular2 application must have one main module that is called “AppModule” and your code should be splitted into various child modules based on your applications.
2.         We do not require to import or declare lazily loading module in root module.
3.         Add the route to top level routing and takes routes array and configures the router.
4.         Import module specific routing in the child module.
5.         And so on.


7. How would you Optimize the Angular 2 Application for Better Performance?
The optimizations are depends on the size of applications, type and other factors but normally we consider following optimizing points i.e.

1.         Consider AOT compilation.
2.         Consider lazy loading instead of fully bundled app if the app size is more.
3.         Keep in mind, your application is bundled and disfeatured.
4.         Keep in mind, your application doesn’t have un-necessary import statements.
5.         Keep in mind, your application’s 3rd party unused library. If exist and not used, removed from your application.
6.         Remove your application dependencies if not required.

8. What are the Securities Threats should we be Aware of in Angular 2 Applications?
As like your other web applications, you should flow in angular 2 applications also.

There are some basic guidelines to mitigate the security risks.
1.     Consider using AOT compilation.
2.     Try to avoid using or injecting dynamic HTML content to your component.
3.     Try to avoid using external URLs if not trusted.
4.     Try to prevent XSRF attack by restricting the REST APIs.

If you are using external resources like HTML, CSS, which is coming from outside the application in case you follow best practice/cleanly your apps.

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

Angular 2 ngOnInit:-
1.      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.
2.      The ngOnInit is called after the constructor and ngOnInit is called after the first ngOnChanges.
3.      The ngOnChanges is called when an input or output binding value changes.

10.  What is the possible order of life-cycle hooks?
Angular 2 Complete lifecycle hook interface inventory:-
1.      ngOnChanges - called when an input binding value changes.
2.      ngOnInit - after the first ngOnChanges.
3.      ngDoCheck - after every run of change detection.
4.      ngAfterContentInit - after component content initialized.
5.      ngAfterContentChecked - after every check of component content.
6.      ngAfterViewInit - after component's view(s) are initialized.
7.      ngAfterViewChecked - after every check of a component's view(s).
8.      ngOnDestroy - just before the component is destroyed.

Angular 2 Lifecycle Events Log:-
1.      onChanges
2.      onInit
3.      doCheck
4.      afterContentInit
5.      afterContentChecked
6.      afterViewInit
7.      afterViewChecked
8.      doCheck
9.      afterContentChecked
10. afterViewChecked
11. onChanges
12. doCheck
13. afterContentChecked
14. afterViewChecked
15. onDestroy


11.  What is Components in Angular 2?
In Angular 2, the components are the main way to build or specify HTML elements and business logic on the page.
In AngularJs 1, we are handling using scope, directives and controllers but all those concepts are using in a single combined that is called components.

The component is the core functionality of Angular 2 app but we need to know to pass the data in to the components to configure them.

To build an Angular 2 application you define a set of components, for every HTML elements, views, and route.

Angular 2 applications must have a root component that contains all other components. That means all Angular 2 applications have a component tree.

Angular 2 Component Summary

·         Angular 2 Component meta-data annotation is used to register the components.
·         Angular 2 components are used to create UI widgets.
·         Angular 2 components are used to split to application into smaller parts.
·         Only one component is used per DOM element.
·         In the Angular 2 components, @View, template and templateUrl are mandatory in the components.


12.  What are differences between Components and Directives?
1.       @Component meta-data annotation is used  to register the components.
@Directive meta-data annotation is used  to register the directives.
2.       The components are used to create UI widgets.
The directives are used to add behavior to existing DOM elements.

3.       The components are used to split to application into smaller parts.
The directives are use to design a reusable components.
4.       Only one component is used per DOM element.
More than one directive are used per DOM element.
5.       In the components, @View, template and templateUrl are mandatory in the components.
The directive do not have @View etc.

syntax error: unexpected token <
Stayed Informed - Angular 2@Output
Syntax is -
System.import('./app/bootstrap/css/boots-trap.css!').then(() => {
System.import('./app/main-app.css!');
});
<div class="row">
<div class="user">
<router-outlet name="userList"></router-outlet>
</div>
<div class="userInfo">
<router-outlet name="userInfo"></router-outlet>
</div>
</div>
const routes: Routes = [
{ path: '', redirectTo: 'home', pathMatch: 'full' },
{ path: 'home', component: HomeComponent },
{ path: 'user', component: userComponent, children: [
{ path: 'userList', component: userListComponent, outlet: 'userList' },
{ path: ':id', component: userInfoComponent, outlet: 'userInfo' }]
}];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule],
providers: []
})
export class RoutingModule { }
import { Inject} from '@angular/core';
import { Http, Response } from '@angular/http';
class UserService {
users: Array<any>;
constructor( @Inject(Http) _http: Http) {
}
}
@NgModule({
imports: [BrowserModule],
declarations: [YourComponent],
bootstrap: [YourComponent]
})
class YourAppModule {}
@NgModule({
declarations: [
AppComponent,
YourComponent,
YourDirective,
YourPipe,
...OTHER DIRECTIVES AND SO ON.
]
})
@NgModule({
providers: [
YourService,
SomeLibraryService,
],
})
@NgModule({
declarations: [YourComponent, YourPipe]
exports: [YourComponent, YourPipe],
providers: [YourService]
})
export class YourModule { }
Angular 2 Modules -
The Angular module — a class decorated with @NgModule — is a fundamental feature of Angular.
JavaScript also has its own module system for managing collections of JavaScript objects. It's completely different and unrelated to the Angular module system.
Angular Modules are the unit of reusability.
Angular modules represent a core concept and play a fundamental role in structuring Angular applications.
Every Angular app has at least one module, the root module, conventionally named AppModule.
Important features such as lazy loading are done at the Angular Module level.
Angular Modules logically group different Angular artifacts such as components, pipes, directives, and so on.
JavaScript Modules -
In JavaScript Modules, every file is one module. In Angular 2, one component is normally a file.
JavaScript also has its own module system for managing collections of JavaScript objects. It's completely different and unrelated to the Angular module system.
Avoid leaking code to the global namespace and thus to avoid naming collisions.
Encapsulate code to hide implementation details and control what gets exposed to the outside.
The Traceur is a JavaScript compiler. The Traceur compiler used to allow us to use the features from the future. The Traceur compiler is fully supported to ECMAScript(ES6) and ES.vNext also.



The main goal of Traceur compiler is to inform the designs of new JavaScript features and also allow us to write the code in better manners and it also prefer, tell us to use design patterns.
13.  What is @Inputs in Angular 2? or How to Passing data into Angular 2 components with @Input?

@Input allows you to pass data into your controller and templates through html and defining custom properties.

@Input  is used to define an input for a component, we use the @Input decorator.

Angular 2 components is the core components of applications but you must need to know “how to pass data into components to dynamically?” and that time you need to define an input component.


14. What is Outputs in Angular 2?
@Output decorator is used to binds a property of a component to send the data from child component to parent component and this is a one-way communication.

@Output decorates output properties and its binds a property of the type of angular EventEmitter.


15.  What is hidden property in Angular 2?
Angular 2 [hidden] is a special case binding to hidden property.

It is closest cousin of ng-show and ng-hide.

It is more powerful to bind any property of elements. Both the ng-show and ng-hide are used to manage the visibility of elements using ng-hide css class. It is also set the display property “display:none”.


16.  How do components communicate with each other?
In Angular 1, I have some ways to communicate between controllers i.e.
1.      $rootScope,
2.      $scope,
3.      $emit,
4.      $broadcast

Now In Angular 2, we have different ways to communicate between components.

A parent component and its children share a service whose interface enables bi-directional communication within the family.


17. How do we display errors in a component view with Angular 2?
In Angular 1, the ng-messages modules are used to help us to display error messages and validation to our forms.

In Angular 2, the ngModel provides error objects for each of the built-in input validators. You can access these errors from a reference to the ngModel itself then build useful messaging around them to display to your users.

And also, we can use the properties “pristine” and “touched” to display error messages.

1.      If we want to display errors after the user fills something in a field, use the pristine property.
2.      If we want to display errors after the user put the focus on a field, use the touched property.


18.  What are the difference between Renderer and ElementRef in angular 2?
ElementRef vs. Renderer -
In Angular Renderer and ElementRef are used for DOM Manipulation and Renderer and ElementRef are used together to get full platform abstraction.

Renderer –
Renderer is a class that is a partial abstraction done the DOM manipulations and the DOM manipulating is not breaking server side rendering or web workers.

ElementRef –
ElementRef is a class that is a partial abstraction done the DOM Manipulations without breakable environments and it also can hold a reference to a DOM elements.

If “ElementRef” is injected to a component, the injected instance is a reference to the host element of the current component.

The ways to get an ElementRef instance looks like,
1.     @ViewChild()
2.     @ViewChildren()
3.     @ContentChild()
4.     @ContentChildren()

In this case the ElementRef is a reference to the matching elements in the templates.


19. What is an Angular 2 Service?
Angular 2 service is a class that encapsulates some methods (GET/POST/PUT) and provides it result as a service for across your application.
The Angular 2 is using services concept and it provide the multiple features to us that are,
1.      Services are singleton objects.
2.      Services are capable of returning the data in the form promises or observables.
3.      Service class is decorated with Injectable decorator.
4.      The Injectable decorator is required only if our service class is making use of some Angular injectable like Http, Response and HttpModule service within it.

Steps for creating an Angular 2 Service:-
There are four steps as,
1.      Import the injectable member i.e.
import {Injectable} from '@angular/core';
2.      Import the HttpModule, Http and Response members’ i.e.
import { HttpModule, Http, Response } from '@angular/http';
3.      Add the @Injectable Decorator i.e. @Injectable()
4.      Export to the Service class i.e.

export class UserService {
       constructor(private _http: Http) {  }
   }


20. What are the differences between Observables & Promises?
1.      Promise:- Promises are only called once and It can return only a single value at a time and the Promises are not cancellable.
2.      Observables:- Observables handle multiple values over time and it can return multiple values and the Observables are cancellable.
3.      The Observables are more advanced than Promises.



21.  How Call Angular 2 Services in Components?
here are four steps to calling a service in component as,
1.      Create or Import the Service to the component class.
2.      Add it as a component provider.
3.      Include it through Dependency Injection.
4.      Use the Service function in the component.


22.  What is Pipes? Why use Pipes?
Pipes transform displayed values within a template.”

Sometimes, the data is not displays in the well format on the template that time where using pipes.
You also can execute a function in the template to get its returned value.

The angular 2 have some additional pipes names that are async, decimal, percept and so on. And also some of pipes not supported in angular 2 that are number, orderBy and filter and these are archiving using “custom pipes”.

Key Points:-
Pipe class implements the “PipeTransform” interfaces transform method that accepts an input value and returns the transformed result.

There will be one additional argument to the transform method for each parameter passed to the pipe.

The “@Pipe” decorator allows us to define the pipe name that is globally available for use in any template in the across application.

For example as,
import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
    name: 'barcode',
    pure: false
})
export class BarCodePipe implements PipeTransform {
    transform(value: string, args: any[]): string {
        if (!value) {
            return '';
        }
        return "****-****_" + (value.length > 8 ? (value.length - 8): '')
    }
}



23.  Why use Pipes?
Sometimes, the data is not displays in the correct format on the template that time where using pipes.

You also can execute a function in the template to get its returned value.


24. What is a pure and impure pipe?
In Angular 2, there are two types of pipes i.e.
1.      pure
2.      impure

The pure pipe is by default. Every pipe has been pure by default. If you want to make a pipe impure that time you will allow the setting pure flag to false.

Pure Pipes:-

Angular executes a pure pipe only when it detects a pure change to the input value. A pure change can be primitive or non-primitive.

Primitive data are only single values, they have not special capabilities and the non-primitive data types are used to store the group of values.

For example for pipe pure,
import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
    name: 'barcode'
})
export class BarCodePipe implements PipeTransform {
    transform(value: string, args: any[]): string {
        if (!value) {
            return '';
        }
        return "****-****_" + (value.length > 8 ? (value.length - 8): '')
    }
}


Impure Pipes:-

Angular executes an impure pipe during every component change detection cycle. An impure pipe is called often, as often as every keystroke or mouse-move. If you want to make a pipe impure that time you will allow the setting pure flag to false.

For example for pipe impure,
import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
    name: 'barcode',
    pure: false
})
export class BarCodePipe implements PipeTransform {
    transform(value: string, args: any[]): string {
        if (!value) {
            return '';
        }
        return "****-****_" + (value.length > 8 ? (value.length - 8): '')
    }
}



25. What is Async Pipe?
Angular 2 provides us special kinds of pipe that is called Async pipe and the Async pipe subscribes to an Observable or Promise and returns the latest value it has emitted.

The Async pipe allows us to bind our templates directly to values that arrive asynchronously manner and this is the great ability for the promises and observables.

Example for AsyncPipe with Promise using NgFor,

@Component({
    selector: 'app-promise',
    template: '<ul> < li * ngFor="let user of users | async">  Id: {{user.id }}, Name: {{user.name }} </li>< /ul>'
})
export class PromiseComponent {
    //USERS DECLARATIONS.
    users = [];

    //FETCHING JSON DATA FROM REST APIS
    userRestApiUrl: string = 'https://api.github.com/users/hadley/orgs';

    //HOME COMPONENT CONSTRUCTOR
    constructor(private userService: UserService) { }

    //GET USERS SERVICE ON PAGE LOAD.
    ngOnInit() {
        this.userService.getUsers(this.userRestApiUrl).subscribe(data => this.users = data);
    }
}

26. How to create a custom Pipes?

The “@Pipe” decorator allows us to define the pipe name that is globally available for use in any template in the across application.



Steps for Creating a Custom Pipe:-
1.      Create a typescript class.
2.      Decorate the class using @Pipe.
3.      Implement PipeTransform interface.
4.      Override transform() method.
5.      Configure the class in application module with @NgModule.
6.      Ready to use our custom pipe anywhere in application.


27.  What is Directives in Angular 2?
 There are 3 types of directives in Angular 2.
1.     Components Directives - directives with a template
2.     Structural Directives - change the DOM layout by adding and removing DOM elements.
3.     Attribute Directives - change the appearance or behavior of an element, component, or other directive.


28. What are components directives?
A component is a directive with a template and the @Component decorator is actually a @Directive decorator extended with template oriented features.

1.     To register a component, we use @Component meta-data annotation.
2.     The directives are used to add behavior to existing DOM elements.
3.     The directives are used to design a reusable component.
4.     Only one component can be present per DOM element.
5.     Multiple directives are used per DOM element.
6.     The directive does not have @View etc.


29. What are structural directives?
The Structural directives are responsible for HTML layout and It is using Angular 2 for reshape the DOM's structure and also removing, or manipulating elements.

30. What are attribute directives?
Attribute directives are used to change the behavior, appearance or look of an element on a user input or via data from the service.

31.  What is router-outlet directive in Angular 2?
Router-outlet directive: - Router-outlet directive is used to render the components for specific location of your applications. Both the template and templateUrl render the components where you use this directive.


32.  What is a structural directive?
The “Structural directives” are responsible for HTML layout. They shape or reshape the DOM structure; it is using for adding, removing and manipulating the elements.

The “Structural directives” is used to enable an element as a template for creating additional elements. If you want to create structural directive that time you should have knowledge of <template> elements and structural directives are easy to recognize.

The two familiar examples of structural directive as,
1.      *ngIf
2.      *ngfor


33.  What is Template Angular 2? Why Use?
A template is a HTML view that tells Angular 2 for render your components in the views.

The Angular 2 templates are very similar to Angular 1 but Angular 2 has some small syntactical changes.                         

You can see the changes as below,
1.         {}: Is use to rendering the HTML elements.
2.         []: Is use to binding properties.
3.         (): Is use to handling your events.
4.         [()]: Is use to data binding.
5.         *:  Is use to asterisk Operations like *ngFor="let item of items; let i=index;”
The templates can be inline or external separate files.

34. What are differences between templateUrl and styleUrls?
Inline templates are specified directly in the component using template and it is more complex for bigger templates. As per expert suggestions, use templates and styles into a separate file, when your code more than 5 to 10 lines.

External templates define the HTML in a separate file and reference this file in templateUrl.

To use a relative path in the templateUrl we must include import component form @angular/core
Some befits for template Urls i.e.
1.               Separations of code
2.               Easy debugging


35.  How to use styleUrls and styles in Angular 2?
The Angular 2 “styles” or “styleUrls” should only be used for css rules and it is affect the style of the template elements.


36.  How to import css using system import?
You do need the “System.import” to bootstrap and run your application.

It can't run without it, and if it does, you might have a cashed version in your browser.

The error is -
This error indication that some of the script files didn't get loaded correctly!







37.  How to Load external css style into Angular 2?
The “styles” or “styleUrls” should only be used for css rules and it is affect the style of the template elements.

This is the best approaches to add styles directly to the components and the view encapsulation is set per component. It is use for some situations.

38.  What is Routing Concepts in Angular 2?
“The Router is use to map applications URLs to application components. There are three main components that you are using to configure routing.”

1.           Routes: - It uses to describe our application's Routes.
2.           Router Imports: - It uses to import our application's Routes.
3.           RouterOutlet: - It is a placeholder component and use to get expanded to each route's content.
4.           RouterLink: - It is use to link to application's routes.

Routes: - The Routes is uses to describe our application's Routes. The “RouterModule.forRoot” method in the module imports to configure the router.

Five concepts that need Routes Representation
1.           Path (a part of the URL)
2.           Route Parameters
3.           Query/Matrix Parameters
4.           Name outlets
5.           A tree of route segments targeting outlets

Syntax:-
RouterModule.forRoot([
            { path: '', redirectTo: 'home', pathMatch: 'full' },
            { path: 'home/:id', component: HomeComponent }, //HERE ID IS A ROUTE PARAMETER.
            { path: 'login', component: LoginComponent },
            { path: 'registration', component: RegistrationComponent },
            { path: '**', redirectTo: 'home' }
        ])

Example,
@NgModule({
    bootstrap: [ AppComponent ],
    declarations: [
        AppComponent,
        HomeComponent,
        HeaderComponent,
        MenuComponent,
        LoginComponent,
        RegistrationComponent
    ],
    imports: [
        UniversalModule, // MUST BE FIRST IMPORT. THIS AUTOMATICALLY IMPORTS BROWSERMODULE, HTTPMODULE, AND JSONPMODULE TOO.
        RouterModule.forRoot([ //RouterModule.forRoot method in the module imports to configure the router.
            { path: '', redirectTo: 'home', pathMatch: 'full' },
            { path: 'home/:id', component: HomeComponent }, //HERE ID IS A ROUTE PARAMETER.
            { path: 'login', component: LoginComponent },
            { path: 'registration', component: RegistrationComponent },
            { path: '**', redirectTo: 'home' }
        ]),
        FormsModule,
        ReactiveFormsModule
    ]
})


Router Imports - The Angular Router is an optional service that presents a particular component view for a given URL i.e.

import { RouterModule, Routes } from '@angular/router';

Example,
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { UniversalModule } from 'angular2-universal';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';

import { AppComponent } from './components/app/app.component';
import { HomeComponent } from './components/home/home.component';
import { HeaderComponent } from './components/shared/header/header.component';
import { MenuComponent } from './components/menu/menu.component';
import { LoginComponent } from './components/login/login.component';
import { RegistrationComponent } from './components/registration/registration.component'


@NgModule({
    bootstrap: [ AppComponent ],
    declarations: [
        AppComponent,
        HomeComponent,
        HeaderComponent,
        MenuComponent,
        LoginComponent,
        RegistrationComponent
    ],
    imports: [
        UniversalModule, // MUST BE FIRST IMPORT. THIS AUTOMATICALLY IMPORTS BROWSERMODULE, HTTPMODULE, AND JSONPMODULE TOO.
        RouterModule.forRoot([ //RouterModule.forRoot method in the module imports to configure the router.
            { path: '', redirectTo: 'home', pathMatch: 'full' },
            { path: 'home/:id', component: HomeComponent }, //HERE ID IS A ROUTE PARAMETER.
            { path: 'login', component: LoginComponent },
            { path: 'registration', component: RegistrationComponent },
            { path: '**', redirectTo: 'home' }
        ]),
        FormsModule,
        ReactiveFormsModule
    ]
})


Router-outlet directive: - Router-outlet directive is used to render the components for specific location of your applications. Both the template and templateUrl render the components where you use this directive.

Syntax :- <router-outlet></router-outlet>

Example
<div class='container'>   
    <div class='row'>
        <router-outlet></router-outlet>
    </div>
</div>

The Route Params: - The route parameter is used to map given URL's parameters based on the rout URLs and it is an optional parameters for that route.

Syntax: -   params: {[key: string]: string}

Example
@NgModule({
    bootstrap: [ AppComponent ],
    declarations: [
        AppComponent,
        HomeComponent,
        HeaderComponent,
        MenuComponent,
        LoginComponent,
        RegistrationComponent
    ],
    imports: [
        UniversalModule, // MUST BE FIRST IMPORT. THIS AUTOMATICALLY IMPORTS BROWSERMODULE, HTTPMODULE, AND JSONPMODULE TOO.
        RouterModule.forRoot([ //ROUTERMODULE.FORROOT METHOD IN THE MODULE IMPORTS TO CONFIGURE THE ROUTER.
            { path: '', redirectTo: 'home', pathMatch: 'full' },
            { path: 'home/:id', component: HomeComponent }, //HERE ID IS A ROUTE PARAMETER.
            { path: 'login', component: LoginComponent },
            { path: 'registration', component: RegistrationComponent },
            { path: '**', redirectTo: 'home' }
        ]),
        FormsModule,
        ReactiveFormsModule
    ]
})

Router-link directive: - Router-link directive is used to link a specific part of your applications.

Syntax :- <router-link></router-link>

Example,
<ul class='nav navbar-nav'>
    <li [routerLinkActive]="['link-active']">
        <a [routerLink]="['/login']">
            <span class='glyphicon glyphicon-Login'></span> Login
        </a>
    </li>
    <li [routerLinkActive]="['link-active']">
        <a [routerLink]="['/registration']">
            <span class='glyphicon glyphicon-Register'></span> Register
        </a>
    </li>
    <li [routerLinkActive]="['link-active']">
        <a [routerLink]="['/Billing']">
            <span class='glyphicon glyphicon-Billing'></span> Billing
        </a>
    </li>
</ul> 


39.  Is it possible to have a multiple router-outlet in the same template?

Yes! We can use multiple router-outlets in same template by configuring our routers and simply add the router-outlet name. You can see in the example.



Syntax-


And setup your route config:






40.  What are cookies in Angular 2?
Angular 2 cookies concept is very similar to the Angular 1.x but Angular2 added only one extra method to remove all cookies i.e. removeAll()

The All cookie methods are
1. get()
2. getObject()
3. getAll()
4. put()
5. putObject()
6. remove()
7. removeAll() - This is new one in angular 2

get() :- This method is returns the value of given cookie key.
getObject() :- This method is returns the desterilized value of given cookie key.
getAll() :- This method is returns a key value object with all the cookies.
put() :- This method is use to set a value for given cookie key.
putObject() :- This method is use to serializes and set a value for given cookie key.
remove() :-This method is use to remove given cookie.
removeAll() :-This method is use to remove all cookies.


41.  What is Dependency Injection (DI) in Angular 2?
Dependency Injection is a powerful pattern for managing code dependencies.

Angular 2 Dependency Injection consists of three things.
              1.       Injector
              2.       Provider
              3.       Dependency

Injector :- The injector object use to create instances of dependencies.
Provider :- A provider is help to injector for create an instance of a dependency. A provider takes a token and maps that to a factory function that creates an object.
Dependency :- A dependency is the type of which an object should be created.



@Injectable() marks a class as available to an injector for instantiation. An injector reports an error when trying to instantiate a class that is not marked as @Injectable().

Injectors are also responsible for instantiating components. At the run-time the injectors can read class metadata in the JavaScript code and use the constructor parameter type information to determine what things to inject.


42.  What is @Injectable()? Why Use?
@Injectable () marks a class as available to an injector for instantiation. An injector reports an error when trying to instantiate a class that is not marked as @Injectable ().
Injectors are also responsible for instantiating components. At the run-time the injectors can read class metadata in the JavaScript code and use the constructor parameter type information to determine what things to inject.


43.  What is @Inject()? Why Use?

Angular 2 @Inject() is a special technique for letting Angular know that a parameter must be injected.

44.  What are the difference between @Inject and @Injectable?
@Injectable () marks a class as available to an injector for instantiation. An injector reports an error when trying to instantiate a class that is not marked as @Injectable ().

Injectors are also responsible for instantiating components. At the run-time the injectors can read class metadata in the JavaScript code and use the constructor parameter type information to determine what things to inject.

Angular 2 @Inject() is a special technique for letting Angular know that a parameter must be injected.

Example as,


45.  What is the purpose of NgModule??
The @NgModule is a new decorator. This module is recently added in Angular 2.

The @NgModule is a class and work with the @NgModule decorator function. @NgModule takes a metadata object that tells Angular “how to compile and run module code”.

The @NgModules page guides you from the most elementary @NgModule to a multi-faceted sample with lazy modules.

The @NgModule main use to simplify the way you define and manage the dependencies in your applications and using @NgModule you can consolidate different components and services into cohesive blocks of functionality.

The Basic Example of @NgModule as,

The @NgModule is a way to organize your dependencies for
1.      Compiler
2.      Dependency Injection


The declarations of @NgModule.declarations as,

The @NgModule providers as,

The @NgModule exporting as,


49.  Angular 2 Modules vs. JavaScript Modules
Angular 2 Modules -

The Angular module — a class decorated with @NgModule — is a fundamental feature of Angular.
JavaScript also has its own module system for managing collections of JavaScript objects. It's completely different and unrelated to the Angular module system.

Angular Modules are the unit of reusability.

Angular modules represent a core concept and play a fundamental role in structuring Angular applications.

Every Angular app has at least one module, the root module, conventionally named AppModule.
Important features such as lazy loading are done at the Angular Module level.

Angular Modules logically group different Angular artifacts such as components, pipes, directives, and so on.

Angular Modules help to organize an application into cohesive blocks of functionalities and extend it with capabilities from external libraries.


JavaScript Modules -

In JavaScript Modules, every file is one module. In Angular 2, one component is normally a file.
JavaScript also has its own module system for managing collections of JavaScript objects. It's completely different and unrelated to the Angular module system.

Avoid leaking code to the global namespace and thus to avoid naming collisions.

Encapsulate code to hide implementation details and control what gets exposed to the outside.
Structure our applications and we can’t use a single file.

Manage dependencies and code reuse.


50. What is Traceur compiler in Angular 2 ?
Now the days Traceur compiler are broadly used in Angularv2.0 because Angular v2.0 are fully used to ES5 and ES6. 

1 comment:

  1. Thanks for sharing this angular 2 interview questions. It is really helpful. Share more like this.
    Angular 2 Training in Chennai | Angularjs course in Chennai

    ReplyDelete