Angular Interview Questions

1. What is Angular?

Angular 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 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 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 features Of Angular?

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 are the key components of Angular?

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


5. How will you handle errors in Angular applications?

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


6. 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] })


7. What is CLI?

Full form of CLI is Command Line Interface, It is a command-line interface tool that you use to initialize, develop, scaffold, and maintain Angular applications directly from a command shell.


8. Explain tsconfig.json file.

It is used to give the options about TypeScript used for the Angular 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 decorators. If not in place, Angular application will not compile.


9. What is the meaning of component life cycle in Angular?

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


10. What are differences between Constructors and NgOnInit?

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().

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. ngOnChanges is called when an input or output binding value changes.

Click here to read more


11. Explain use of NgOnInit in Angular?

Angular 2 provide  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 Angular 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.”


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


13. What are the differences between Angular Components and Directives?

@Components @Directive
 @Component meta-data annotation is used  to register the components. @Directive meta-data annotation is used  to register the directives.
The components are used to create UI widgets. The directives are used to add behavior to existing DOM elements.
The components are used to split to application into smaller parts. The directives are use to design a reusable components.
Only one component is used per DOM element More than one directive are used per DOM element.
In the components, @View, template and templateUrl are mandatory in the components. The directive do not have @View etc.

 


14. What are services in Angular?

Angular 2 service is a class that encapsulates some methods (GET/POST/PUT) and provides it result as a service for across your application.


15. What are the features of Angular Service?

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


16. What are the steps for creating an Angular 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) {  }

  ....

}


17. What are the steps for Calling an Angular Service in the Angular Component class?

There are four steps to calling a service in component as,

  1. Create and 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.


18. What are Angular directives? Explain with examples.

A directive is a custom HTML element that is used to extend the power of HTML. Angular 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.


19. Explain Routing in Angular.

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' }

    ])


20. Angular Templates - template vs. templateUrl? How to Use Inline and External Templates?

A template is a HTML view that tells Angular for render your components in the views.

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.


21. Name few common filters available in Angular?

  • uppercase: Converts string to uppercase.
  • lowercase: Converts string to lowercase.
  • date: Converts a date to specified format
  • Number: Converts number to string.
  • currency: Converts number to a currency format.
  • filter: Select a subset of items from an array.

 


22. What is SPA (Single Page Application)? Explain the SPA implement with Angular?

Single Page Applications are web applications that show/load a single HTML page and dynamically update/changes that page as the user interacts with the app. In an SPA the page never reloads, though parts of the page may refresh. This reduces the round trips to the server to a minimum. This way application gets faster than normal.

It’s a concept where we create a single shell page or master page and load the webpages inside that master page instead of loading pages from the server by doing post backs. Angular routes are used in Angular to emplement SPA.


23. What are the different type of Directive in Angular?

There are three kinds of directives in Angular:

  • Components directives: One of most common directive we frequently use with each component. It is decorated with the @component decorator
  • Structural directives: It is used to modify the HTML DOM by adding, removing elements. Stuctural direcitves are easy to recognize by using an asterisk (*). For example, *ngIf, *ngFor
  • Attribute directives: It change the appearance or behavior of an element, component, or another directive. For eample, NgStyle


24. What is string interpolation in Angular?

It is a databinding technique which is used to output data from TypeScript file to HTML template(view part). It uses double curly braces to display data from component to the view. See the syntax below:

<h2>{{data.heading}}</h2>

 


25. What is Data Binding and what are different types of Data Binding in Angular?

Data binding automatically keeps your page up-to-date based on your application's state. You use data binding to specify things such as the source of an image, the state of a button, or data for a particular user.

Types of Data Binding:

  1. String Interpolation
  2. Property Binding,
  3. Event Binding,
  4. Two Way Data Binding.

The binding punctuation of [], (), [()], and the prefix specify the direction of data flow.

  • Use [] to bind from source to view.
  • Use () to bind from view to source.
  • Use [()] to bind in a two way sequence of view to source to view.


26. Explain Property Binding?

Property binding helps to bind value from TypeScript to the properties of HTML elements(view).

Example:

<div>

  <img [src]='imgPath' />

</div>


27. Explain Event Binding?

This is third type of data binding available in Angular which helps to make the web page interactive, Whenever user performs any action over view then this data binding helps to send the request to the controller part(TypeScript code) to perform the respective task for the action performed by the user.

Example,

<button (click)='addToCart(item.id)'> Add To Cart </button>

 


28. Explain Two way Data Binding.

Two way data binding is the combination of property and event binding. It automatically syncronizes the data between the view and the Model(TypeScript code). Angular provides us a directive, ngModel, to achieve two-way data binding.

data binding

 

<div class="container">

  <input [(ngModel)]='location' />

  <br/><h1>Entered Location: {{location}}</h1>

</div>

 


29. What can be the reasons of using Angular inspite of other popular library/framework like ReactJS?

Below are the reasons of choosing Angular for any applications:

Complete Framework: Angular is a complete framwork for developing any type of web application. We don't need to depend for any basic task in the web development. It have complete ecosystem for developing apps.

Google Supports: Google is behind Angular and making huge change to make it faster as compared to other frameworks.

Community Suppport: Angular has bigger community support than other javascript frontend libraries/frameworks.

Declarative UI: Angular uses HTML to render the UI of an application as it is a declarative language and is much easier to use than JavaScript.

 


30. Why Angular uses TypeScript not JavaScript?

Below are the few reasons:

  • TypeScript completely follows Object Oriented Programming (OOP), which is better for bigger apps to maintain robust and clean code; this improves the code quality and maintainability.
  • TypeScript provides highly productive development tools for JavaScript IDEs and practices, like static checking.
  • TypeScript is superset of JavaScript so TypeScript has additional features than JavaScript.
  • Code written in TypeScript are testable.
  • TypeScript Code can be converted into plain JavaScript Code if needed.


31. What is Transpiling in Angular?

As we know, Browser don't understands TypeScript code so we need to convert the TypeScript code to JavaScript to work on browser. The compiler takes the TypeScript code and converts it into JavaScript. This process is commonly referred to as transpiling.