Monday, January 23, 2017

Angularjs 2 Interview Questions

Angularjs 2 Interview Questions

This Angularjs Tutorial is focused on Angularjs 2 Interview Questions with detailed answers. For Angularjs 1.x, we already have published a detailed anguarjs article with all related concepts here. We are focused to provide more practical details with real time scenarios and complete source code in order for user to grasp the newer version of angularjs. This angularjs tutorial is divided in two parts, starting from basic understanding about angular2, reason for newer version, setting up the environment for angularjs 2, creating a basic application in angularjs 2 and further covering more advanced topics.Angularjs 2 Tutorial

Angularjs 2 Interview Questions List

What is Angularjs 2? Is that true that Angular2 is entirely a new thing (revamped version) as compared to Angularjs 1.x?

What is Angularjs 2?

The main disadvantage of Angularjs 1x was it was not build for modern web, therefore,  it was such a  framework which cannot work with Modern Web Components, therefore, mobile development with Angularjs 1x was not very straight-forward, moreover, used to push it was not standard against Modern framework such as ReactJs. In order to get rid of all these disadvantage and be suitable for modern web components based development, Angularjs team has released Angular 2.0.
Angularjs 2 has most of the architectural component from such as module, directive, service, dependency injection, change detection and modularity. However, in Angular 2.0 existing all architectural building blocks from Angularjs 1.x are available in more better as well as improved format. The reason, some may argue that it is a completely new framework as it has shifted the coding to Type script. However, from architectural point of view Angularjs 2   is not a new web framework, rather, its just a better framework.
Back to top

List down the advantages and disadvantages associated with Angular2?

AngularJs 2 Advantages:

  • Get Rid of ‘$digest already in progress when calling $scope.$apply()’ Exception: In Angularjs 1.x, there are multiple times, developer get the exception ‘’ $digest already in progress when calling $scope.$apply()’. The  reason is, Angular 1.x  did not support digest cycle finished event,  because such event might trigger further events as well as changes which can trigger an infinite loop for  the current digest cycle. Developer used to make very distinctive reasoning in order to decide when to call $scope.apply or $scope.digest, which was not always very simple .Moreover, developer needs to use $timeout event to force Angular finish event to end the current digest cycle.  In Angular 2.0 Zone has made a revolutionary change in case of change detection and  zones mechanism  is capable of deciding whether to end digest cycle or not. Therefore, one of the major advantages of Angular 2.0 is change detection with Zone mechanism.
  • Improved Performance: Another significant disadvantages of Angularjs 1.x was its poor performance, In case of ng-repeat the performance issue was really a blocking issue. However in Angular 2.0, the change detection mechanism does not travel the entire DOM tree to detect a change, rather its only travel a part of it, therefore, the performance has been improved significantly.
  • Improved modularity & Dependency Injection: Angular modules in Angular 1.x are mostly architecture to group a number of related functions and then used as container for dependency injection containers. However, in 2.0 modular development and component isolation has made it more easier to instantiate a component and used it in its scope. Inheritance has been introduced in component isolation, therefore, a child service can be injected while it will inherits all the services of its parent. Child injectable component or service is also capable of overriding their parent’s functionality.
  • This is more friendly for mobile development and server side rendering.

AngularJs 2 Downside/Disadvantages:

  • Those who are not familiar with typescript would take longer time to learn.
  • Most of the component need to be developed as the online community is still at the beginning stage.

What is ECMAScript ES6/ES7? Breifly explain both. Which version is supported by Angularjs 2.

ECMAScript is a standard for modern scripting-language specification. Initially, it was It was JavaScript, now its being changing to ECMAScript.
6th Edition – ECMAScript 2015:
ECMAScript 2015 is the 6th Edition. This version has significant contribution for:
  • Class Inheritance
  • Iterators for loop
  • Python-style generators and generator expressions
  • Advanced set for collections
  • number and math enhancements
  • Promises
  • Metaprogramming for virtual objects and wrappers and so on.
Although, ES6 still does not support browser. Therefore, compiler such as Traceur are required to compile EC6 code to pure javascript on the fly in browser.
7th Edition – ECMAScript 2016:
The 7th edition, officially known as ECMAScript 2016, has been finalized in June 2016.
Which version is supported by Angular2?
Angular has used 6th Edition – ECMAScript 2015 (Es6). However, there are configuration available to try some experimental feature from  7th Edition – ECMAScript 2016 (Es7).
  • Inheritance of component has become so easy. Now Angular 2.0 can be developed using  Object oriented thinking. Inheritance has been possible for javascript. A number of libraries has been developed to support this concept. However, with ES2015 all those  nonstandard abstractions can be got rid of. As  ES2015 defines an easier inheritance.

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.
Traceur itself is written in ES6, compiled to ES5. Details can be found here.
Back to top

How to setup development environment for Angular2? Please follow the step by step approach with code configuration/screenshots?

In this section, the development environment setup has been described. Angularjs 2.0 application can be developed using:
  1. angular-cli: This is a command line tool for Angularjs 2.0 application development which support live coding and deployment instantly. This is much easier and much straight forward.
  2. systemjs: This is the traditional way of developing angularjs application. This way has been described in details later in Part-2.
Development Angularjs 2.0 Application Using ANGULAR-CLI:
Pre-requirement:
  1. 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’
  2. Install angular-cli (https://cli.angular.io/)
    • Install angular-cli by following command
Install Angular CLIThe next step is to create the application from command line.
Development Angularjs 2.0 application Using angular-cli:
For example, if I want to create an angularjs 2.0 application in folder project named ‘helloworld’. The steps are described in the answer of an Interview Question later in this series.
Back to top

How to develop your first Angularjs 2 application in steps to render simple text?

We are going to follow a step by step approach to develop our first Angular2 Applicatio
  1. Open the command prompt on the workspace folder called ‘project’.Angularjs 2 Application
  2. Run command ‘ng new <project name>’. Lets suppose the project name is ‘helloworld’. This command will create a new project named ‘helloworld’. This may take few minutes.AngularJs Tutorial ng new
    This command will create the main app component and relevant template along with typings, tsconfig, styles and e2e configuration.Angular2 Application
    This step will also install all necessary required dependency library for the new project.Inside ‘helloworld’ project folder, there will be these following files created.Angular2 Project Folder
    The source code for the application are inside ‘src’ folder as following:AngularJs 2 Tutorial SourceIndex.html is the main html file for the application.Angular2 Application IndexTherefore, in app.component.ts <app-root> has been described as the main selector.Angularjs 2 Application app-root
    Now as we want to render a simple text. So in our AppComponent, we have taken a variable named ‘title’ and the template url of AppComponent is app.component.html.Next step is to render title in app.component.html as following
  3. The next step is to run the project with the command ‘ng serve’.a. Go to the ‘helloworld’ folder by running  ‘cd helloworld’ command
    b. Run ‘ng serve’ in command promptAngular2 ng serve Command
  4. From browser run ‘http://localhost:4200’and the output would be as following:Angularjs 2 Application Output

How to handle Routing in Angular2? What are the main routing components? Explain all related concepts like router-link, router-outlet, @RouteConfig and RouteParams in Angular2.

Angular2 has improved so many features from AngularJs 1.x, Router component is one of them. In order to use routing mechanism, there are few steps as following need to be performed.
Goal: 
For this section, the goal is that, we have a website with two pages (1) home and (2) About and we have to setup Routing mechanism to route these two pages:

What are the main routing COMPONENTS?

Angular2 provides 3 different components for routing configuration:
  1. Routes is the configuration to describe application’s different routes
  2. RouterOutlet is a “placeholder” component that holds the view for each route
  3. RouterLink is a directive to link to routes

Routes:

Routes is an object to describe the routes of the application. For instance, here is an example for our previously specified goal.
We have configure routes which is an array of Route. Each entry of the array is  The complete list of possible fields used in this configuration are as following:
  1. path – url of the route used by the matcher DSL.
  2. component –name of the target component.
  3. pathMatch – specifies the matching strategy, example : full.
  4. redirectTo -url that will replace the current matched segment in case of redirection.
  5. outlet – name of the outlet used as a placeholder for the component. If there is no outlet it would be placed in <router-outlet>
  6. canActivate – array of DI tokens used to find CanActivate handlers.
  7. canActivateChild – array of DI tokens used to find CanActivateChild handlers.
  8. canDeactivate – array of DI tokens used to find CanDeactivate handlers.
  9. data is additional data provided to the component via ActivatedRoute.
  10. resolve is a map of DI tokens used to look up data resolvers.
  11. children is an array used to define nested routes.

Router Directives

Angular RouterModule has 3 different directives. Such as:
  1. router-outlet
  2. router-link
  3. routerLinkActive
router-outlet:
router-outlet is a component from angular/router library. The router is the placeholder to display views inside  <router-outlet> tags. As the routes changes, the view inside the <router-outlet> tags also change accordingly.
router-link:
router-link directive is an alternative of HTML href property. The syntax is as following:
router-link directive can also handle query parameter. For example, once we land in /hoem/events page, it shows a list of events , if we want to go to directly one of the events page, we can just put the iid of that specific event and can land of the event details page for event 01. For this purpose, we use [queryParams] binding. [queryParams] takes an object such as {‘id’:01} and can
Firstly, We have bound router-link directive to events array as following:
Now inside app.router.ts we have configure the queryParams binding as following:
Otherwise, if we want to pass the queryParams in an object , we can also do that as following:
OR
routerLinkActive:
The RouterLinkActive directive toggles css classes for active RouterLinks based on the current RouterState. This cascades down through each level in our route tree, so parent and child router links can be active at the same time. To override this behavior, we can bind to the [routerLinkActiveOptions] input binding with the { exact: true } expression. By using { exact: true }, a given RouterLink will only be active if its URL is an exact match to the current URL.

How to  handle Routing in Angular2?

There are following steps to complete achieve this Goal, such as
  1. Create App Router Module
    a. Configuration different Paths
  2. Import RouterModule to AppModule
  3. Create Router-Outlet view and associated component
  4. setup router-link directive

Defining Routes

Let’s create a file called app.routes.ts in the root of the app folder. This file will describe the configuration for routers for the application. There would be two different type of routes one those users can access without login and others can be accessed only after login. In this document, we will only discuses about routing without authentication.
Firstly, there is an empty route. This is the route the app will launch with. Then there is redirectTo ‘login’, which will change our path to login when it encounters an empty route. After that, we have our pathMatch. If pathMatch: full is provided, the router will apply the redirect if and only if navigating to ‘/’.
The next route is points to LoginComponent. The path is set to login, which is what we will see in the address bar when we navigate to this route. The component that will be navigated to is the LoginComponent. The same for the route with ‘about’ and ‘register’.
We also have the HomeComponent. The path is ‘home’, and the component to launch is the HomeComponent. Home has one nested route. If the path is only /home this will points to DashBoardComponent. However, if the path is /home/events it will points to EventComponent.
Then the last route we will add is a wildcard route. This will match any routes that we have defined. This is also why we added the redirect. If we didn’t, our app would start at this route since we start from a route that is not defined, an empty route.
After adding the redirect, any route that we type that doesn’t exist will get our error page.
Here the routes has been passed as the argument to RouterModule.forRoot() so that the RouterModule in our imports is able to use the RouterOutlet and RouterLink components in this module.

Import This AppRouterModule

In app.module.ts, we have to import the AppRouterModule along with other components.

Create Router-Outlet view and associated component

For this example, we have placed a placeholder on app.component.html as following:

The Main AppComponent

Setup router-link directive

Now we have to write the router-link to place the actual link on html. Therefore, we change the app.component.html and add the router link as following:

How to add authentication in client side using Angularjs 2.0?

For this example, we will create a new component to signup user using JSONToken.
1.Create a new Service called ‘auth’ using following command:
Angularjs 2.0 Authentication
2. Create authenticated and non authenticated Router in AppRouter:
3. Create a new component called ‘AuthCcomponent’:
4. Now for http://localhost:4200 the page will be redirect to http://localhost:4200/app-auth
Back to top

Explain Angular 2.0 Framework Architecture with the help of diagram?

Angularjs 2.0 can be defined simply as following:
HTML Template + Javascript/ Typescript code compiled to Javascript = Angularjs 2.0 app
Every Html template, there is a component. These components manages corresponding templates. Sometimes, components are injected with services for any particular service.
The following figure describes Angularjs 2.0 framework in a nutshell.Angular 2 Architectural Components
From the figure, we can see that Angularjs 2.0 framework has 9 main building blocks such as:
  1. Metadata
  2. Module
  3. Component
  4. Template
  5. Data Binding
  6. Event Binding
  7. Directive
  8. Service
  9. Dependency Injection

More Angularjs 2 Interview Questions and Answers:

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.
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.
In brief, metadata defines the properties for any module or component. Metadata helps any class to process and execute.
Back to top

What are Modules in Angularjs 2.0?

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.
Back to top

What are Components in Angular 2.0

Component in Angularjs 2:

This is main interesting feature of Angular 2.0. Now it is possible to develop angular app in more object oriented way. It is also possible to pass parameter between components.
In this section lest create two component and communicate between them.
The first component is PeopleComponent which will pass a list of person object to another component called ‘PersonComponent’ to show a list of person on card. The steps to create a component is very simple.
1. Create the template ‘people.component.html’
2. Create class for the component called ‘people.component.ts’
@Component decorators define the selector for the template of this component, the file for the html template has been defined by using  templateUrl , css file has been configured using styleUrls and any services that are required are configured by using providers.
3. Add the component in the main app module
4. Place the selector in parent template, in this case put it on app.component.html
5. Create the second component called PersonComponent.
Here PersonComponent take an input called ‘person’. Therefore, any native element declared with ‘person-detail’ selector will take an input called ‘person’.
6. Add the PersonComponent to AppModule.
7. Pass the input from the template of PeopleComponent.
Communicating among components is very easy in Angular 2.0.
Back to top

Briefly explain Angularjs 2 Directives?

Directives in Angularjs 2:

Along with component, Angular 2.0 has also have two other kind of directives such  as  Structural directives and Attribute Directive. Directives are used to change the behavior as well as layout of the DOM elements.  It is possible that the same DOM element may have a number of directives. However, in case of component it is not possible, any DOM element can have only a single component.
Lets create a progress bar directive as following:Directives in Angularjs 2
This progress bar will take two input one to determine the width % and other is the class type for the design.
  • Lets start with template
    Therefore, there are two input progressbar and contextType; progressbar will determine the width of the progressbar and contextType will determine the class type.
    => If  contextType =1 , then class = .progress-bar-success
    => If  contextType =2 , then class =.progress-bar-info
    => If  contextType =3 , then class = .progress-bar-warning
    => Otherwise, class = .progress-bar-danger
    Here in the example, [progressbar] =’60’ and [contextType]=’2′
  • Create a class called Progerssbar
    Mention the selector for the directive.
    In order to change the behavior of the DOM element, it needs to be declared
    In order to change the class for the element, the Rendered is also need to be declared
    Now based on the  input progressbar , we have to change the width of the nativeelement
    Next requirement is to change the class
    Directive can also be used for event handling. As for example, here @HostListening is kept listening for a ‘mouseenter’ event and as soon as there is a ‘mouseenter’ event trigger, it perform respective change in behaviour.

Briefly explain Data Binding in Angularjs 2.0?

Data Binding in Angularjs 2:

From angular 1.x to angular 2.0, the data binding has not been changed in template way. However, from performance point of view this has been changed dramatically.
There are two types of data binding available in angular 2.0
  • One way
  • Two way
However, any variable is available within the scope of the component and they can be passed from one component to another component. This way, one of the significant concentration that developed used to give in case of variable declaration in angular 1.x has become much simpler.
The details has been described in questions later in this Angularjs 2 Interview Questions Series.

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.
There is another way of binding event to DOM element is as following

1 comment: