Must Have Angularjs 2 Interview Questions – Part2

By | January 1, 2017

This is Part-2 in Series of Angularjs Tutorial focused on Angularjs 2 Interview Questions with detailed answers. We strongly recommend to go through previous parts to understand the basic details about setup, configuration, creating our first Angularjs 2 Application etc. So, having a look on below Angularjs Tutorials will be helpful.

Angular 4 is out now. We can use Angular 4 to develop applications that are cross platform with maximum speed and performance. More on Angular 4 here.

Indeed Job Trends

More Advanced Angularjs Tutorial List

Angularjs 2 Interview Questions in Series

What are the Templates in Angularjs 2? Give a practical example of using Templates in angular2 with source code.

Templates in Angular2:

Simply the HTML for each component is the template in Angular2. There are not too much difference between template in Angular2 and the template in Angular 1.x. However, there are significance changes in syntax due to most of the Angular 1.x core directive such as ng-Controller, ng-change, ng-model has been changed in the template in Angular2.

Earlier, in Angularjs 1.x the template used to look like as following, it required ng-app to map to the Angularjs application. Ng-controller was required to map to respective controller. However, now both of these directives are not used in Angular2.Angularjs 2 Templates

However, in Angular2, each component can have in-line template using ’template’ or can have a template html file using ‘templateUrl’. For example, in Figure for component given earlier, the html template for app.component.ts is app.component.html file in the same folder.Angular2 Template Tutorial

Now if 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.

We can also develop the same page using template in component as following:Angularjs 2 Template Tutorial

Both of the case the output would be as following:Angularjs Tutorial Output

Some Syntax for Template in Angular 2


Curly brackets are used to render any variable defined in component.


Square brackets are used to bind to any property. For example, in the first example here the value of the <input>  has been bind to the variable called ‘myName’.Angular2 Binding Property

Therefore, output would look like.Angular2 Template Syntax Example

In all three example, [] has been used to bind to any property of the html tag.

  • EVENT HANDLING USING ()Angularjs 2 Event Handling

Output: For every change in the input field, the increment method will increase  the value of the variable val by 1.

Angularjs 2 Event Output

  • TWO-WAY DATA BINDING Using [()]:

The ng-model directive of Angularjs 1.x has been replaced by [(ngModel)] where [ngModel] and (ngModelChange) has been combined. This is used for two way data bindings.Angular2 Two Way Data Binding

  • * for Directive DOM
    In the following example, * has been used for ngFor
  • Some Invalid expression in Angular 2:

The following expression are invalid in Angularjs 2.0 .

(=) (+=) ( -=) (new ) (;) (,) (++) (–) (|) (&)

| is used for Pipe reason, therefore (|) is an invalid expression.
Back to top

Explain the Angular2 data binding concepts including property binding, class binding, style binding and event binding with appropriate example and source code.

Angularjs 2 Data Binding:

Usually Angular supports two different type of data binding, such as:

  • One Way data binding
  • Two Way data binding

One way Data Binding:

One way binding is usually used to render any variable on template which has been declared in component. {{}}, curly brackets are used for data rendering. This is a one-way binding as the variable is managed in component.

One way binding is also used for property binding,for example, hidden attribute of <span> element.

Two way Data Binding:

In combination of property binding and event binding, in Angular 2.0 two way data binding has been performed.

In order to make a change in Component from template, event binding is used to emit a function and performed the event.

The change in component is reflected in view / template is performed by property binding.Two way data binding

This two way databinding can be also achived by using [ngModel] to the input property and (ngModelChange) event to output property, these two angular core directives set the value of the ‘name’ variable and listen to the expected events on componentsin order to reflect the change of the variable in template to component.

Here the property [value] has been set to the variable name, and (input) event updates the value of the name variable as the input value changes.

Two–way data binding can also be possible by combining [property-binding] and (event-binding) through another directive [(ngModel)] to implement two-way data binding.

What is Property Binding?

In the first example, the value property of the <input> HTML component has been bind to the variable ‘name’. OnInput of <input> the variable name will be changed to the input event’s target value given as input by the user. [ ] has been used for property binding and ( ) has been used for function binding.

The output is as following:Angularjs 2 Value Property

The second example, shows how the attribute of any button can be bind in AngularJs 2.0.

The common format to bind attribute is as following
[attr.<attribute name>]=”variable Name”

For example, here the tooltip/title for the button has been set to the variable ‘actionName’.

Angularjs 2 Attribute of ButtonWe can pass variable from one component to another component. Here the preant component is passing friend variable as a input to my-friend component.

Summarized Example:

Target Example
Attribute <button [attr.title]=”actionName”>{{actionName}} with Aria</button>
Property of a HTML element <input [value]=”name” >
Property of a Component <my-friend [friend]=”friend”> </my-friend>

What is Class Binding?

For example, if we want to have a div with class ‘panel-primary’ if a variable isprimary is true, otherwise the class for the div would be ‘panel-success’.

So the format of class binding is as following

Angular2 Class BindingNow if we change the variable isprimary = false;Class Binding in Angular2

The output would be:Angularjs2 Class Binding

What is Style Binding?

For example, if we want to have a div with text color red if a variable isprimary is true, otherwise the color for the div would be ‘green’.

So the format of class binding is as following:

Angular2 Style BindingAs here isprimary=true, therefore, output would be as following:Angular2 Style Binding Output

Style binding can be also done by using [ngStyle] as following:

ngStyle can be bind to a variable defined in component such as:

Here, error is a variable:

Style Binding in Angular2ngStyle can also be bind to function. This way is used for conditional style change. For example, in the following example, if the variable ‘isprimary’ is true the changeColor() method will return success variable as style object otherwise it will return error style object defined earlier in the same component.ngStyle in Angularjs 2

What is Event Binding?

Event binding with Angular 2.0 is much easier and there are lot of stuff could be done.

  • Call a simple event from the component by clicking the button.
  • It is also possible to pass any parameter to the even.
    And in the component:
  • This is possible to detect which event has been triggered from component. It is also possible to detect which kind of event it is.
    There are different kind of event those could be triggered directly from the HTML element.  Here both and mouseleave action trigger the same event. However if we want to change the class based on these two different events. For example, on-mouseenter the div will be of red color and on-mouseleave the color will be green.
  • Another important feature of Event binding is EventEmitter, which enables to multiple components to share events real time.

Back to top

Define Forms in angular2? Create a basic Registration Form in Angular2 with fields as Username, Password, FirstName, LastName, Phone Number, Email. Apply the basic form validation too.

With Angular1, form was completely template based and every functionality need to be e implemented separately for form validation. However, in AngularJs 2.0 the new helper Class called FormBuilder helps to explicitly declare forms in respective component. FormBuilder also provides a set of form control’s validators for basic validation. If there is any advanced validation is required it is possible to create a new validators. FormBuilder has another cool feature which is  asynchronous validation. Use case, like if we need to know if the username is already in the system, we can use this asynchronous validation to send a HTTP request to database to check the availability of the username.

In our example we are going to develop a basic Registration Form in Angular2 with fields as Username, Password, FirstName, LastName, Phone Number, Email.Forms in Angularjs 2

  • Import FormsModule and ReactiveFormsModule in AppModule.

  • Lets create the template registration.component.html.
    Therefore, in the component there would be a variable called ‘registrationForm’ and a method called registerUser. Next step is that for each field, we create a new Formontrol as following for username, we have to create a form Control in component called ‘userName’. Also add errorMessage.
  • Build the form in component.
    => Import  FormGroup, Validators,FormControl from @angular/forms
    => Define the formControl for each field such as username, password, firstName,lastname,email and phoneNumber.

    • Single Validator:
    • Composite Validator: This is also possible to combine more than one validator. For exmaple,
  • Create custom validation. For, example, if we want to check if the email format is valid or not.
    • Lets create a validation service class
    • And inject that ValidationFormService service to RegistrationFormComponent
  • Create the method for validation in ValidationFormService.
  • Add the validator to email formControl.

Back to top

More Angularjs 2 Interview Questions and Answers:

What is dependency Injection w.r.t Angular2? Describe how to use D.I in Angular2 with the help of an example.

In order to inject any service later in any of the component, the service class needs to be declared as @Injectable.

  • Create a method in DataService that will return the nth Day of the week, where n is the input number from 1 to 7.

    The next step is to inject the service to any component by declaring the service as providers.

  • Add providers in AppComponent’s metadata.Angular2 App Component Metadata
    Now, if there is an instance of the service inside component, the component can access any service provide by DataService class through the instance of it.
  • Add the DataService variable in the constructor of the App Component.Angular2 App Component
  • Call the service from app component.

    Any method from DataService class can be accessible from appComponent with it’s instance.

Back to top

Learn Professional Web Development in AngularJS while building 10 unique Web Apps.
77 lectures, 14.5 Hours Video, All Levels

  • Your First Angular Website
  • Web Template Store
  • myContacts App
  • ngSocial Facebook App
  • Job Directory
  • KnowledgeBase
  • User Authentication App
  • Instagram Gallery
  • PubNub Chat
  • AutoFind

And also we will find Quiz at the end of each application to verify the skill improvement.

What are Services in Angular2? How to make a Service to Dis ribute Data? Explain with an example.

The beauty of the service in angular2 is as it can be injectable to any components. There are some facts of service of Angularjs 2.0 as following:

  • Services are singleton. Every component use individual instance of the service.
  • Usually the instance of component are created inside the constructor of the component

How to Make a Service to Distribute Data?

For example, if we want to create a DataService and use that Service in App Component.

Example 1: Use a service to determine the nth day of the week. Here n = 1,2,3,4,5,6 and 7.

The steps in order to use a service is as following:

  • Create a new class called  ‘DataService’  and save the file as data.service.ts.
  • Make the new class @Injectable.
  • Create a new methods getalldays() to get all the days of the week and getdaysofweek to get a particular day of the week.
  • Import DataService In AppComponent.DataService in Angular2
  • Add providers in AppComponent’s metadata.Angular2 App Component Metadata
  • Add the dataservice variable in the constructor of the App Component.Angular2 App Component
  • Call the getdayofweek method of DataService.
  • The output would be as following:Angular2 Services

Back to top

How to make an HTTP Request in Angular2? Give a proper example of making an HTTP request using Angular2.

For example, lets call a Rest API get call from App Component. In order to serve this purpose, we have to create a new service and inject that in AppComponent.

Create a Service to access HTTP Request:

  • Create a file called src/app/data.request.service.ts.
  • Import necessary libraries.
    • As service need to be injected in components, therefore several Web service dependencies such as Http, Response would be required.
    • Http Request need to be async and change in real time, therefore, we would also need Observable or Promise.
  • Declare the service class as @Injectable.
  • Initialize the constructor of the new service with HTTP Object.
  • Create a method  that will take the response of the HTTP Request  as input and convert it to JSON.
  • Create a method to handle the error message for the response of the HTTP request.
  • Make the http GET Request
    Here map will call formatData Method and convert the response to json object. Catch will be called if there is any error in this will be delat with the handleError method.

Update app.module.js:

In app.module.ts add we need to import HttpModule:

Inject Service in Appcomponent:

  • DataRequestService’ is imported in AppComponent.
  • Component decorator’s providers metadata has ‘DataRequestService’.
  • In the constructor of the component, a variable ‘_dataRequestService’  of type ‘DataRequestService’ Service’ has been declared. This variable will be used to use any method of type ‘DataRequestService’ Service’.
  • AppComponent has an observable variable called ‘countries that stores the response of the API call.
  • Then, inside ngOnInit(), the method has been called.
  • The Observable has been subscribed here in method getAllCountries(). In subscribing there are three distinctive callbacks: the first receive the response as new value for @Input countries, the second one is for any errors and the last one is used to represent the function to be invoked when the sequence of incoming data is complete and the HTTPs request is successful.
Change App.Component.html:
Output View:

HTTP Request using Angular2
Back to top

Create a basic example of implementing AutoComplete in Angular2?

In order to implement we have to follow the following steps:

  • Open command prompt run ‘ng new autocomple’ command to create a new project called ‘autocomplete’.Installing Angularjs 2
  • Go to autocomplete folder and run ‘ng serve’ and from browser run ‘http://localhost:4200’.The web page will look like:ng Serve in Angularjs 2
  • In a separate command window Create a new directive called Autocomplete with  the command ‘ng generate directive autocomplete’.Generate Directive in Angularjs 2
  • Create a new service with the command ‘ng generate service country’.ng generate service

Finally output would be:Angular2 AutoComplete

If we select one item from the dropdown:Angularjs 2 AutoComplete
Back to top

Angular 4 is out now. We can use Angular 4 to develop applications that are cross platform with maximum speed and performance. More on Angular 4 here.

What is System Js in Angular2? How to config System Js in Angular 2? Please elaborate in detail.

What is System Js in Angular2?

The role of systemJs in angular 2 are as following:

  • System.js is universal Module loader. This is very popular as module loader for loading ES6, AMD, CommonJS and any other global scripts in the browser and NodeJS. Once this plugin loads the required module, typescript.js can compile TypeScript code on-the-fly into ES5 in browser.
  • This is mainly a mapping configuration file to find out the library file location
  • CONFIG API  ( helps to config different system config parameter in order to load different modules from different location.

How to Config System Js in Angular2?

Initialize a Project:
  • Create a new folder called ‘helloworld’.
  • Run npm init command as following:Run NPM Init Command
  • This will create package.json with the following format:
    Angularjs 2 Package.json
    So at this moment we have the project name ‘helloworld’ and some basic information such as license, author and so on.
  • However, for an angularjs 2.0 project we need some more configuration. For example, firstly, we need the core dependencies. A minimum valid list of dependencies could be as following:
  • Next it requires some additional dependencies to compile and deploy for typescript as following:
  • On script we need to add the command for continuous ts compilation
    Everytime, ‘npm run’ command will be executed, the tsc  command will be triggered and this will compile the TS code into JS code. ‘ tsc -w’ is watcher which will continue to listen for any changes in project’s TS code to compile.
  • Therefore, finally the package.json would look like as following:
  • Run ‘npm install’ at the root folder of the project, this will install all required libraries.
Install Typings:
  • Install typings using the ‘ npm install typings -global’ command on command prompt.
  • Now we need a config file for additional configuration need to be performed by Typescript compiler. For example, we need to add core, jasmine and node to the project. In order to perform the task,
    • Run ‘typings install dt~core-js –global –save’ command.typings install in Angular2
      This command will install typings and create typings.json file in the root folder of the project.Typings file folder in Angularjs 2
      At the moment, typings.json file will look like this:typings json
    • Run ‘typings install dt~jasmine –global –save’ command.Angular2 typings install
    • Check if there is any available update by running this command ‘typings install dt~node –global –save’.typings install update
      If there is any update available, this will look like as following
    • Run following command to get the updates
      At this moment, typings.json file will look as following:GlobalDependencies in Angular2
Setup the Typescript Compiler:

The next step is to create tsconfig.json file at the root folder of the project.  tsconfig.json is used to configure TypeScript compiler in order to compiles TypeScript code of project to JavaScript.Setup TypeScript Compiler in Angularjs 2

Create Systemjs.config.js file:
  • Create a new file at the root folder of the project called systemjs.config.js. For now we can take a sample file from Angularjs 2.0  Plunker . In this config file, there are a number of properties need to be configured.
Configure System Js in index.html:

Create index.html in src folder:

First add system.config.js

Next import System import with app called ‘app’.

Create AppComponent:

Create App Module:

Create main.ts:Create main ts in Angularjs 2

  • WINDOWS ONLY run npm install -g webpack webpack-dev-server typings typescript to install global dependencies.
  • Run ‘npm start’
  • On browser run ‘localhost:8080’Angular2 App with SystemJs

Back to top

How to use @HostListener Decorator to implement an infinite scrolling?

  • Create a new component in existing angularjs application called ‘infinitescroll’.Hostlistener in Angularjs 2
  • Import HostListener and Inject to the component.
  • Declare the Document, here the target element.
  • Implement windowScroll method and bind it to window:scroll event.
    HostListener helps to continuously listening for any event trigger.

Back to top

How to implement End2End testing using Angular CLI?

Test Case 1: If we want to test if the getAllCountries() method of CountryService is working properly.

If the service class has been created using ng command from angular cli tool, there would be already related spec class created.Angular2 End to End Testing

Now in country.service.spec.ts file, we have create the use cases as following:

Now from command line run the command ‘ng test’. A new window will be opened with test status.Angular2 ng test

This will show all the errors and warning in console as below:Angular CLI

End 2 End Test

For end to end testing Create end-to-end tests in e2e/searchcountry.e2e-spec.ts

Run the command is ‘ng e2e’.

Code Coverage

For code coverage run ‘npm run coverage’

The report file will be generated inside ‘coverage’ folder.Code Coverage

Learn Professional Web Development in AngularJS while building 10 unique Web Apps.
77 lectures, 14.5 Hours Video, All Levels

  • Your First Angular Website
  • Web Template Store
  • myContacts App
  • ngSocial Facebook App
  • Job Directory
  • KnowledgeBase
  • User Authentication App
  • Instagram Gallery
  • PubNub Chat
  • AutoFind

And also we will find Quiz at the end of each application to verify the skill improvement.

Back to top

Concluding Remarks
Hopefully, this Angularjs 2 Tutorial Series will be helpful for developers to understand the technology in more practical way and prepare well for Angularjs Interview Questions.

Top Technical Interview Questions and Answers Series:

Latest Angularjs Jobs – Updated Daily

[php snippet=9]