Angular2 Interview Questions

1: What is angular2?

Angular JS2 is a modern framework for app development. It is essentially a structure that helps you create applications faster by providing a number of service and objects that makes things easier for app developers.

The Angular JS2 is a dramatic upgrade to the previous version of the framework. It is really a rethinking of how applications should be built.

One of the primary reasons for a lot of these changes is performance. So Angular JS2 apps run 3-5 times faster than the previous version.



2: List some advantages of Angular 2 over Angular1.

Angular 2 is a re-written version of Angular1 and not an update. The best way to compare Angular 2 and Angular 1 is by finding out the new features in Angular 2. This way we will be able to find out the advantages of Angular 2 over Angular1 precisely. So, some of the advantages of Angular 2 are:-

 

Angular 2

Angular1

Angular 2 is a mobile-oriented framework

Whereas Angular1 was not developed with mobile base in mind.

Angular 2 is a versatile framework, i.e. we have more choices for languages. We can use ES5, ES6, Typescript or Dart to write an Angular 2 code

Whereas an Angular1 code can written by using only ES5, ES6 and Dart. We don’t have many choices of language in Angular1.

Nowadays, the controllers are replaced by components and Angular 2 is completely component based.

Whereas Angular1 was based on controllers whose scope is now over.



3: Explain the new features Of Angular 2?

Fully Component Based- It is fully component based. It is not used to scope and controllers as it was in angular1 and Angular 2 are fully replaced by components and directives.

 

Directives- The directive can be declared as @Directive notation.

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 the ability to add the functionality of components at runtime It 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: What the reasons of using Angular2?

A.     It is entirely component based.

B.     Better change detection while development

C.     Angular2 has better performance than angular1.

D.     Angular2 has more powerful template system.

E.     Angular2 much more testable

F.    Provides to nested level components.

G.     Angular2 execute run more than two programs at the same time.

H.  In Angular2, local variables are defined using prefix (#) hash.

I.  TypeScript can be used for developing Angular 2 applications.

J.  Better syntax and application structure



5: What are the key components of Angular 2?

Angular 2 has the following components −

Modules − This is used to break up the application into logical pieces of code. Each piece of code or module is designed to perform a single task.

Component − This can be used to bring the modules together.

Templates − This is used to define the views of an Angular JS application.

Metadata − This can be used to add more data to an Angular JS class.

Service − This is used to create components which can be shared across the entire application.



6: How will you handle errors in Angular 2 applications?

Angular 2 applications have the option of error handling. This is done by including the ReactJS catch library and then using the catch function.

The catch function contains a link to the Error Handler function.

In the error handler function, we send the error to the console. We also throw the error back to the main program so that the execution can continue.

Now, whenever you get an error it will be redirected to the error console of the browser.



7: What is Dependency Injection? Explain with example.

Dependency injection is the ability to add the functionality of components at runtime. Let's take a look at an example and the steps used to implement dependency injection.

 

Step 1 − Create a separate class which has the injectable decorator. The injectable decorator allows the functionality of this class to be injected and used in any Angular JS module.

@Injectable() 
   export class classname {  
}

Step 2 − Next in your appComponent module or the module in which you want to use the service, you need to define it as a provider in the @Component decorator.

@Component ({  
   providers : [classname] 
})



8: What is CLI?

 

Command Line Interface (CLI) can be used to create our Angular JS application. It also helps in creating a unit and end-to-end tests for the application.



9: Explain tsconfig.json file.

It is used to give the options about TypeScript used for the Angular JS project.

{ 
   "compilerOptions": { 
      "target": "es5", 
      "module": "commonjs", 
      "moduleResolution": "node", 
      "sourceMap": true, 
      "emitDecoratorMetadata": true, 
      "experimentalDecorators": true, 
      "lib": [ "es2015", "dom" ], 
      "noImplicitAny": true, 
      "suppressImplicitAnyIndexErrors": true 
   } 
}

Following are some key points to note about the above code.

1. The target for the compilation is es5 and that is because most browsers can only understand ES5 typescript.

2. The sourceMap option is used to generate Map files, which are useful when debugging. Hence, during development it is good to keep this option as true.

3. The "emitDecoratorMetadata": true and "experimentalDecorators": true is required for Angular JS decorators. If not in place, Angular JS application will not compile.



10: What is the meaning of component life cycle in Angular 2?

The component life cycle hooks overview the life cycle sequence and the interfaces. Angular manages the life cycle of a component. Angular creates it, renders it. It can also create and render its children. It also checks when its data bound properties change. It can even destroy it before removing it from the DOM. The life cycle hook offered by angular provides the visibility into these key life moments and the ability to act when they occur. The components go through an entire set of processes or life cycle right from its initiation to the end of the application. There are a number of life cycle hooks which are listed below: –

There are a number of life cycle hooks which are listed below: –

  1. ngOnChanges
  2. ngOnInit
  3. ngDoCheck
  4. ngAfterContentInit
  5. ngAfterContentChecked
  6. ngAfterViewInit
  7. ngAfterViewChecked
  8. ngOnDestroy

 



11: 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.



12: Explain use of NgOnInit in Angular2?

In Angular 1 versions, ngInit is called when template is re-rendered. In other words “ng-init” is called, when I take turns back to a page.

 

In Angular2, there is no “ng-init” but we can create a ways like this using the directive and ngOnInit class. Angular 2 provides life cycle hook ngOnInit by default.

 

The ngOnInit is invoked when the component is initialized and invoked only once when the directive is instantiated. It is a best practice to implement these life-cycle interfaces.

 

According to Angular2 Doc, “The ngOnInit is called right after the directive's data-bound properties have been checked for the first time, and before any of its children have been checked. It is invoked only once when the directive is instantiated.”



13: What is the difference between observable and promises?

The differences between observable and promises are:-

  1. Observable is a more powerful way of handling HTTP asynchronous requests. Whereas, A promise handles a single event when an asynchronous operation completes or fails.
  2. An observable is like a stream which allows passing zero or more events where the callback is called for each event. Whereas, A promise eventually calls the success or failed callback even when you don’t need the notification or the result it provides anymore.
  3. Observable works with multiple values for a particular time. Whereas, Promises works with and even returns a single value at a time.
  4. Observables can be canceled. Whereas, Promises cannot be canceled.
  5. Observable supports map, filter, reduce and similar operators. Whereas, Promises have more readable codes with try/catch and async/await.
  6. In observable, one operator ‘retry’ can be used to retry whenever needed. Whereas, Promises cannot be retried. A promise should have access to the original function that returned the promise in order to have a retry capability.



14: Angular 2 components vs directives

Angular 2 components vs directives

                       

@Components

@Directive

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.



15: What is 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.



16: What are the features of Angular 2 Service?

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.



17: What are the 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) {  }

 

  }



18: What are the steps for Calling an Angular 2 Service in the Angular 2 Component class?

There 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.

 



19: What are Angular 2 directives? Explain with examples.

A directive is a custom HTML element that is used to extend the power of HTML. Angular 2 has the following directives that get called as part of the BrowserModule module.

ngIf

The ngif element is used to add elements to the HTML code if it evaluates to true, else it will not add the elements to the HTML code.

Syntax

*ngIf = 'expression'
If the expression evaluates to true then the corresponding gets added, else the elements are not added.

 

ngFor

The ngFor element is used to elements based on the condition of the For loop.

Syntax

 

*ngFor = 'let variable of variablelist'
The variable is a temporary variable to display the values in the variablelist.

 



20: Explain Routing in Angular2

The Angular Router enables navigation from one view to the next as users perform application tasks. 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' }

    ])



21: Angular 2 Templates - template vs. templateUrl? How to Use Inline and External Templates?

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.

 



22: What's New in Angular 4?

It includes some major improvements and functionality

1.  Smaller & Faster Apps

2.      View Engine Size Reduce

3.      Animation Package

4.      NgIf and ngFor Improvement

5.      Template

6.      NgIf with Else

7.      Use of AS keyword

8.      Pipes

9.      HTTP Request Simplified

10.   Apps Testing Simplified

11.   Introduce Meta Tags

12.   Added some Forms Validators Attributes

13.   Added Compare Select Options

14.   Enhancement in Router

15.   Added Optional Parameter

 

16.   Improvement Internationalization