Top Angular 2 Interview Questions and Answers - Essential Guide for Job Seekers

Questions

112

Last updated

Sep 5, 2024

To survive in the modern industry and to earn a very good salary, learning only JavaScript programming language is not sufficient, you must move on to learning JavaScript Frameworks also i.e., Angular. It doesn’t matter if you are thinking to start your career in software development or are already a software developer, you will always find Angular 2 Interview Questions useful. This is an open-source component-based UI framework that is written in TypeScript and is mainly used in building web, mobile, and desktop applications in HTML and JavaScript. Angular is an evolved and upgraded version of Angular JS and is invented by Google. For writing codes, Angular provides many language choices like Typescript, Dart, ES5, ES6. It supports both data and property blinding which allows a user to control DOM i.e., Data Object Model by binding class and HTML properties.

Quick Facts About Angular 2
What is the latest version of Angular? Angular 14 released on 2nd June 2022
When did angular 6 release? 14th September 2016
Who is the developer of Angular 2? Google
What language does Angular use? TypeScript
License MIT License
Official website https://angular.io

Most Frequently Asked Angular 2 Interview Questions

Here in this article, we will be listing frequently asked Angular 2 Interview Questions and Answers with the belief that they will be helpful for you to gain higher marks. Also, to let you know that this article has been written under the guidance of industry professionals and covered all the current competencies.

Q1. What is Angular 2 and also explain its components?
Answer

Angular 2 is the upgraded and evolved version of AngularJS, a JavaScript framework that was invented by Google. Angular 2 is used for building single-page web or mobile applications.

Components are essential elements of Angular 2 apps, and an application can have a number of components. In Angular 2, components perform all the tasks that were done by scopes, controllers and directives, such as creating or adding Data, logic, and custom elements.

In Angular 2 a component consists of the following:
  • Template
  • Class
  • Metadata
Q2. List the new features of angular 2?
Answer

These features stand out:

  • Use of TypeScript
  • Built-in support for mobile app development
  • Improved performance
  • Support for 3 directives types - component, decorator, and template.
  • Enhanced Dependency Injection
  • Increased data binding
  • Supports component-based architecture
  • Cross-platform and cross-browser support

Note: This is a very important angular 2 interview question and generally it is asked in every angular interview.

Q3. What is directive in Angular?
Answer

Directives are the extended HTML attributes and they are also the most important features of Angular applications. They introduce syntax or markup.

There are 3 kinds of directives-
  • Components
  • Structural
  • Attribute
Q4. What is routing in angular 2?
Answer

Routing is what lets in you to create Single Page Applications. AngularJS routes allow you to create distinct URLs for one of a kind content material in your application. It helps in redirecting users to exceptional pages based totally on the alternative they pick out on the main page. AngularJS routes enable one to show more than one content depending on which route is chosen. A route is unique in the URL after the # sign.

Q5. What is pipes in Angular 2?
Answer

In all Angular version from 2 onwards, there is a common feature called Pipes. This feature helps developers create custom pipes.

Pipes are used to write display-value transformations that developers can declare in their HTML. A pipe inputs data and transforms it into the required output.

Pipes in Angular2

There are some pipe provided by angularjs are given below-

  • Uppercase/Lowercase Pipe
  • Date Pipe
  • Currency Pipe
  • JSON Pipe
  • Async Pipe
Q6. How to redirect to 404 or other path if the path does not exist in Angular 2?
Answer

Using angular routing you can navigate from one view or page to another while performing your tasks. You can configure a URL to redirect to the next URL. This feature can be handled to address the "404 Not Found" problem. Using location services in Angular routing you can go back and forward through the history of pages.

Syntax : We can use {path: '/OUR_PATH', redirectTo: ['redirectPathName']}

{path: '/404', name: 'PageNotFound', component: NotFoundComponent}

Q7. What is the use of codelyzer in angular 2?
Answer

It is an open source tool for running and checking if the pre-defined coding guidelines were followed or not. It does static code analysis for typescript and angular projects.

It runs on top of tslint and coding conventions are defined in tslint.json file. Editors such as Visual Studio Code support codelyzer by doing basic settings.

Q8. What is lazy loading in angular 2?
Answer

Lazy loading allows developers to load different code pieces on demand. For instance, if you have a retail application that has different departments like garments, groceries, electronics, etc. If you load all the sections, in the beginning, your application will be slow. This is when you need lazy loading. It helps the application load faster because it loads only parts that the user wants to see.

This interview questions on angular 2 are always a level up and thus a little tough to crack.

Q9. What is the use of Typescript in Angular2?
Answer

The biggest benefit of TypeScript is tools like advanced autocompletion, refactoring and navigation. Because TypeScript developers do not need to rewrite to migrate to JavaScript. They can do it one module at a time. In addition, because of TypeScript, the code is easier to understand.

Q10. What is the difference between Angular 2 and AngularJS?
Answer
  AngularJS Angular 2
1. No mobile support Mobile-oriented
2. Only supports Dart, ES6 and ES5 Offer more language choices
3. Easy to set up Dependent on libraries. Requires efforts to set up.
4. Based on controllers and scope Component-based.
Q11. What do you mean by module in angular 2?
Answer

In Angular 2, a module groups the various components, pipes, directives, and services in a way that assists them in combining with other modules for creating an application.

A module can be used to hide or export pipes, directives, components and services.

Q12. What are observables in angular 2? Explain
Answer

An observable is an array where data arrives asynchronously.

Observables can help developers manage asynchronous data and are used within Angular, including event system and HTTP client service. Angular uses Reactive Extensions (RxJS), a third-party library, to use Observables.

Q13. What is event emitters in Angular 2 and how it works?
Answer

Any change that occurs in the component gets propagated from the existing component to its children. If this change needs to be reflected its parent component, you can use using Event Emitter api to emit the event.

EventEmitter is class in @angular/core module that is used by directives and components to emit events.

@output() somethingChanged = new EventEmitter();

You can use somethingChanged.emit(value) to emit any event. You can do this in setter when the value is changed in the class.

Q14. What is the difference between directive and component in Angular 2?
Answer
  Components Directive
1. To register, use @Component meta-data annotation To register, use @Directive meta-data annotation
2. Used to create UI widgets and break up app into smaller components Use to design re-usable components and add behavior to existing DOM element.
3. Only one component allowed per DOM element Many directives allowed per DOM element.
4. @View decorator is mandatory Does not use View.
Q15. What are the security threats should we be aware of in angular 2?
Answer
  • Avoid injecting dynamic Html content
  • Sanitize external HTML
  • Do not put external URLs in the application
  • Use AOT compilation
  • Prevent XSRF attack by restricting api
Q16. What is decorator in angular 2?
Answer

Decorators allow developers to configure classes as elements by putting metadata on them.

The most common decorators are @Component one for components and @Injectable one for classes.

Decorators are new in TypeScript, and were not available in AngularJS. Angular2 onwards offers four types of decorators and each plays a unique role - Class, Property, Method, and Parameter.

Q17. How do you declare a global variable in Angular 2?
Answer

The simplest way is to put the variables in a file and export them. In order to use global variables, you can use an import statement.

'use strict';

export const name='bestinterviewquestion.com';

After that, we can export this file where we want to use these global variables value.
import * as myGlobalsFile from './globalfile';

Q18. How to pass data into components with @Input in Angular 2?
Answer

You can do this through property binding feature in Angular2. In order to bind data to components, you need to create a custom property bind. This can create it via “input” binding for passing data from one component to another. You can create the custom input binding via the @Input() decorator!

Q19. What is services and also explain its features in angular 2?
Answer

Services allow greater separation of concerns in Angular applications. They also provide modularity by allowing developers to extract common functionalities out of components. Adding Services to Angular applications makes components free from data access code.

 

Service has the following features:

  • Singleton, i.e. only one instance of service will exist throughout the application.
  • Capable of returning data in the form of Observables and promises.
  • Decorated with @Injectable() decorator
Q20. How do observables differ from promises?
Answer
  Observable Promise
1. Used from the library RxJS.
import { Observable } from 'rxjs';
Built-in API.
2. Can show multiple values using setInterval() method Can resolve only one async task and cannot be used again
3. Can unsubscribe from the observables no longer needed. A promise cannot be canceled.
4. Lazy. Observable is called only when we subscribe. Not lazy.
5. Rich set of operators in the library like map, filter, pipe, retry, etc. No such additional features available
Q21. Explain the steps for creating a services in Angular 2?
Answer

Here are the steps:

  • Import injectable member
  • Add @Injectable Decorator
  • Export Service class

 

Here is the syntax:

import { Injectable } from '@angular/core';
   @Injectable()
   export class MyCustomService {
}

Q22. How do you create a custom pipe in Angular?
Answer

In Angular 2, you can create custom pipes. The simplest way is as follows.

import { Pipe, PipeTransform } from '@angular/core';
    @Pipe({name: 'Pipename'})
    export class Pipeclass implements PipeTransform {
    transform(parameters): returntype { }
}

Q23. How to use styleUrls and styles in Angular 2?
Answer

This information is trending in angularjs 2 interview questions for experienced professionals.

In Angular 2, styles or styleUrls affect the style of template elements. The built-in properties in the component Decorator allow developers to encapsulate styles directly as part of their components.

 

Both style and styleUrls are arrays, which means that for styles, you can apply many definitions for each position. For styleUrls, you can split up different style rules into different style sheets.

Q24. What are the difference between @injectable() vs. @inject() in angular 2?
Answer
  @Injectable @Inject
1. Aims to set metadata of dependencies to be injected into constructor Tells Angular what parameter must be injected
2. Without it, no dependency can be injected Only needed to inject primitives
Q25. What is @ngmodule in Angular 2? Explain
Answer

It configures the injector and compiler, and assists in organizing things together. This class is marked by the @NgModule decorator. It can identify module's directives, components, and pipes, making them public as required through the exports properties so that they can be used by the external components.

Q26. What is AOT compilation?
Answer

The AOT compilation converts Angular HTML and TypeScript codes into JavaScript code at some stage in the construct section earlier than the browser can down load and run the code.

Here are benefits of compiling with AOT:

  • Lesser asynchronous requests
  • Smaller download size of Angular framework
  • Detects errors easily
  • Fast rendering
  • Improved security
Q27. What are the advantages & limitation of AOT compilation?
Answer
Advantages-
  • Fast download
  • Quicker rendering
  • Reduces Http Requests
  • Catches errors during the build phase
Disadvantages-
  • Only works with HTML and CSS Not other file types.
  • Must maintain bootstrap file AOT version
  • Must clean-up before compiling.
Q28. What is the best solution to solve requestAnimationFrame is not defined in angular?
Answer

The requestAnimationFrame is not defined” is an Angular universal server running issue. The best solution for this issue is to search for requestAnimationFrame and ensure it's only called when the user is in a browser, not in the server. We can do this by reviewing if there is a nativeElement present on a component ElementRef.

class blahComponent implements OnInit {
    constructor(private elRef:ElementRef) { }

    ngOnInit() {
        if (this.elRef.nativeElement) {
           /** here goes your code */
        }
    }
}

Q29. How to write all the console.log statements to a file in Server?
Answer
  • Using the flags enables "logging" from the command line.

It will make sure that information is locked internally along with console.log (). This lock file is known as chrome_debug.log, and it can be located in the directory.

  • Now you have to filter the log file
Q30. What is CLI in Angular 2?
Answer

It is a command-line interface which is used to build angular apps. We can construct & start a project very quickly with the help of CLI.

You can download CLI from its official website https://cli.angular.io

The command for install Angular CLI

npm install –g angular-cli

Q31. How do you check if angular CLI is installed?
Answer

To check this, you need to make sure that node is installed and then check if angular CLI is installed.

  • Open a command prompt using cmd.
  • Type node -v and npm -v to ensure node is installed.
  • Type ng -v
Q32. Is angular 2 Object Oriented?
Answer

Yes, Angular 2 is a true object-oriented development framework.

Q33. What is the purpose of tsconfig.json in Angularjs?
Answer

It allows us to specify the root level files. The compiler options required to compile a TypeScript project. It determines that the said directory is the TypeScript project root. Here is a JSON file describing to define a tsconfig.json file containing different parameters of the compilerOptions property:

{

    "compilerOptions": {
    "noImplicitAny": true,
    "module": "system",
    "removeComments": true,
    "strictNullChecks": true,
    "sourceMap": true,
    "allowUnreachableCode": false,
    "outFile": "../JS/TypeScript/BestInterviewQuestion.js"
  }
}

Here is an example of these options.
  • target: It is used for the compiled output.
  • module: It is used in the compiled output. the system is for SystemJS, common for CommonJS.
  • moduleResolution: It is used to resolve module declaration files (.d.ts files). With the node approach, they are loaded from the node_modules.
  • sourceMap: generate or not source map files to debug your application.
  • emitDecoratorMetadata: emitDecoratorMetadata emit or not design-type metadata for decorated declarations in the source.
  • experimentalDecorators: It enables or not experimental support for ES7 decorators,
  • removeComments: remove comments or not
  • noImplicitAny: It is used to allow or not the use of variables.
Q34. How to convert the input to lowercase or uppercase in angular 2?
Answer

The filter is used to converting the input to all lowercase and uppercase in Angularjs.

Example

<div>

Best Interview {{Question}}

Best Interview {{appList[0] | lowercase}}

Best Interview {{appList[1] | uppercase}}

</div>

Q35. What is injectable in angular2?
Answer

It is a very important application in the designing pattern, and Angular 2 has its own framework. Injectable is an essential ingredient that provides modularity to Angular 2. Injectables are provided by associating them with injector type.

Q36. What is Router-link directive in Angular 2?
Answer

The router-link derivatives enable the navigation from any specific view to the other. It works immediately as a user is performing application tasks. The link can directly arise from browser and navigation is done on the basis of user action like the click of an anchor tag.

The router link directive gives control to the router for anchor tag elements. It also binds a clickable HTML to the route to enable the navigation. The routerlink directive can easily be bound to an array, E.g.

<a [routerlink] = "[ '/ heroes']" >Heroes</a>

Q37. What is Traceur compiler in Angular 2?
Answer

Traceur compiler takes classes, generators, and other features from ECMAScript edition 6 (ES6) and compiles it into JavaScript ES5 that runs on the browser. This means developers can use the code from a future version that has more features and encourages design patterns.

Q38. How to create a singleton service in Angular 2?
Answer
Here is the steps to create a singleton service-
  • Import the injectable member using import {Injectable} from '@angular/core';
  • Import the HttpModule, Http and Response members’ as import { HttpModule, Http, Response } from '@angular/http';
  • Add the decorator @Injectable()
  • Export –
    export class UserService {
       constructor(private _http: Http) { }
    }
Q39. How to create a component in Angular 2?
Answer
  • Import the top-level component using import { Component } from '@angular/core';
  • Describe the component using the @ symbol. Create instances of @Directive, @Injectable, @RouterConfig etc.
  • Add meta-data like selector, providers, styles, template.
  • Export the component
  • Bootstrap the component

import { Component } from '@angular/core';
import { bootstrap } from '@angular/platform-browser-dynamic';

@Component({
selector: 'my-test',
styles: [`
h1 {
color:#000000;
padding:5px;
}
`]
template: `
<h1>Hi There! This is {{componentName}}.</h1>
`
})
export class TestComponent {
componentName: 'TestComponent'
}
bootstrap(TestComponent);

Q40. What are angular 2 hooks?
Answer

In Angular apps, hooks are functions that are called on particular stages of a component’s life. Hooks are essential if your app is based on the component architecture. Example for hooks is $onInit, $onChanges, etc. which are properties pre-defined by Angular and can be exposed on component controllers.

Q41. What is dependency injection in Angular?
Answer

Angular has a robust DI framework that gives declared dependencies to a class upon instantiation. To inject a service, you must first create and register the injectable service.

import { Injectable } from '@angular/core';
@Injectable({ providedIn: 'root', })
export class SampleService { constructor() { } }

Q42. How to enable lazy loading in Angularjs?
Answer

With lazy loading, JS components can be loaded asynchronously on activation on a specific route.

  • Download and install ocLazyLoad.js
  • Add the module in the application
  • Load the file in the required controller
  • Add to the router’s code as

resolve: {
     loadMyCtrl: ['$ocLazyLoad', function($ocLazyLoad) {return $ocLazyLoad.load('routerState');
}]}

Q43. What is the difference between annotation and decorator in Angular 2?
Answer
Annotation Decorator
Used by Traceur compiler Used by Typescript compiler
Annotation creates the attribute ‘annotations’ that stores arrays and pass metadata to the constructor of the annotated class. It is a function that gets the object that needs to be decorated (or constructed). They can change the attributes of the object as necessary.
Annotations are hard-coded Not hard-coded
Example – import {Component} from 'angular2/angular2'; Example - import {ComponentAnnotation as Component} from 'angular2/angular2';
Q44. What are the advantages of Angular 2 over Angular?
Answer
Advantages of Angular 2 over Angular are given below-
  • Simpler to Learn
  • Simpler Dependency Injection
  • It’s is a platform not only a language:
  • Improved Speed and Performance: No $Scope in Angular 2, AOT
  • Modular, cross-platform
  • Flexible Routing with Lazy Loading Features
  • Benefits of ES6 and Typescript.
Q45. What is the Life Cycle Event to check whether the Dom is fully loaded?
Answer

Modal footer is basically used when the template is fully loaded. User needs to write the code inside the ngAfterViewInit then users will not get the footer element. Thus, footer modal is life cycle event which is used to check whether the Dom is fully loaded or not.

Q46. What is the configuration required for caching of static resources like images, css and js in Angular 2?
Answer

During Development Mode, caching for static resources can be done through the Design of Tools. If you want to cache on the production stage, you need to check and update the Server-End Settings accordingly.

Note: These are basic angular 2 interview questions that are asked for a position as SDE in Angular Development.

Q47. What is the difference between constructor and ngOnInit?
Answer
Constructor ngOnInit
This one is a default class method which gets called when we create new objects. It's an Angular managed life cycle hook to indicate the completion of the component.
A constructor is mostly used to inject dependencies. We use this to perform initialization logic even if the logic doesn't depend on DOM, DI and input bindings.
Q48. What is hidden property in Angular 2?
Answer

In Angular 2, hidden property or [hidden] is a special case binding used to hide property. It can be compared close to ng-show and ng-hide, but more powerful to bind any property types of elements.

<div [hidden]="!active">
  Hello, this is an active area!
</div>
Q49. What is @input and @output in Angular 2?
Answer

Both @input and @output are decorators. The decorator @Input is used to bind a property within one child component to receive value from the parent component, whereas we use the @output decorator to bind the property of a component to send data from child component to parent component or calling component.

Q50. How to display the error message from backend in angular2?
Answer

To display error message in Angular 2 from backend, we have to set the error message equal to an angular variable, and then check whether that variable exists to conform whether to display it or not.

<div *ngIf="errors" class="alert alert-danger">
    {{ errors }}
</div>

 

Q51. What is primeng and how can it be used with angular2?
Answer

PrimeNG is a rich UI component collection dedicated to Angular. Widgets present here are completely open-source and free to use. It’s simple, lightweight yet powerful and optimized for responsive cross-browser touch.

Q52. How would you optimize the application for better performance in angular 2?
Answer

To optimize an application for optimal performance in Angular 2, we have to follow the below-mentioned steps.

  • Use of AOT compilation.
  • With a large-size app, use lazy loading instead of the fully bundled app.
  • Avoid un-necessary import statements in the application.
  • Remove unused and unnecessary 3rd party libraries from the application.
  • If not required, consider removing application dependencies.
Q53. What is tree shaking?
Answer

The Tree Shaking is a concept of dead code elimination from projects. The code present in your project but neither referenced nor used will be dropped here. It will eliminate the unused modules during the build process, making user application lightweight.

Q54. How to define custom typings to avoid editor warnings?
Answer

To avoid editor warning whilst defining customized typings, we have to prolong the kind definition for an external library as a accurate practice. Without altering any node_modules or current typings folder, we have to create a new folder named “custom_typings" and put all our customized kind definitions there.

Q55. What is shadow dom and how it is helping to perform better in angular 2?
Answer

Shadow DOM is an integral part of Web Components standard while enables users for style encapsulation and DOM tree. It helps users to hide DOM logic behind other elements. With the addition to it, we can also apply scoped styles to elements without showcasing them to the outer world.

Q56. How to use {}, [], [] and [()] in template using Angular2?
Answer

All these symbols such as {}, [], [] and [()] are used to express data, event binding, templating concerns and property binding. {} is used for interpolation
[] is used of property binding
[()] is used for event binding

Use of {} symbol

import {Component} from 'Angular2/core';
@Component({
selector: 'cars-app',
template: `
<h1>BMW</h1>
<h2>Total {{ totalCars }}</h2>
` }) export class CarsApp {
totalCars: number = 985;
}

use of [] symbol

Through special attributes on HTML elements, Every DOM property can be written.

Use of [()] symbol

The common syntax of event binding attribute is— ([Name of DOM event]) =”[Template expression]”

Q57. How you can load external css style?
Answer

To allow a load of external CSS styles in Angular 2 to affect component contents, we have to change view encapsulation which presents styles to components referring “bleed into”.

@Component({
   selector: 'some-component',
   template: '<div></div>',
   styleUrls: [
      'https://bestinterviewquestion.com/style.css',
      'app/local.css'
   ],
   encapsulation: ViewEncapsulation.None,
})
export class SomeComponent {}

Q58. What are differences between templateUrl and template?
Answer

Inline templates are specified in the component directly using the template and External templates define the HTML in a separate file called templateUrl.

Q59. What is ViewChild and ContentChild in Angularjs?
Answer

Both ViewChild and ContentChild are used to perform component communication in AngularJS. The parent components use ViewChild or ContentChild to access child components. Template’s part of directive, element or component is referred to ViewChild, whereas element or component projected in the template us referred as ContentChild.

Q60. What is the use of polyfills.ts file in Angular 2?
Answer

In Angular 2, the polyfills.ts file is used to make user application compatible for various browsers. The code we write in Angular 2 is mostly in ES6, which is not compatible with Firefox or IE, and requires few environmental setups before they wither get viewed or used in browsers.

Angular offers Polyfills.ts file to help users with the required setup.

Q61. What are lifecycle hooks and why it is important?
Answer

In Angular, lifecycle hooks are functions which will be called at specific points of a component lifecycle in Angular applications.

They are highly crucial for a component architecture based application.

Q62. What happens when the page containing Angular based application loads?
Answer

When a page containing Angular based application loads, these below-mentioned scenarios will be completed.

  • The browser will load the HTML document and evaluate it.
  • The file for AngularJS JavaScript will be loaded and the Angular global object will be created.
  • Finally, the JavaScript that registers controller function will be executed.
Q63. What is deep linking in Angular 2?
Answer

In Angular 2, deep linking is a process of the URL that will take to users to a specific page or content directly without crossing the application from the homepage. The deep linking process helps with website or application indexing so that search engines can easily crawl these links.

Q64. What is the factory method in Angular 2?
Answer

As services are reusable singleton objects in AngularJS which is used to organize and share codes across the application, they can be injected into filters, controllers, and directives. Angular 2 offers three ways to create a service; factory, service, and provider.

The factory function allows developers to include some logic before creating the object and returns the created object. The syntax for factory function is as follows.

app.factory('serviceName',function(){ return serviceObj;})

Q65. What is the difference between a service() and a factory()?
Answer
factory() service()
The factory function allows developers to add certain logic before the creation of an object. This one is a constructor function which helps creating the object with a new keyword. Developers can add functions and properties to a service object by using the keyword.
It will return the created object. It returns nothing.
Syntax:
app.factory('serviceName',function(){ return serviceObj;}
Syntax:
app.service('serviceName',function(){})
Q66. What are promises in angular 2?
Answer

Promises in Angular 2 execute asynchronous functions in serial order by registering promise object. Additionally, promises are provided by build-in $q service. Promises have generated a new way into native JavaScript as a part of the ES6 specification

Q67. What is rootScope in angular 2?
Answer
Available with all Angular applications, rootScope is the scope HTML element created scope which contains ng-app directive. It is available in the entire application.
Q68. What is difference between rootScope and scope in Angular 2?
Answer
rootScope

It's an AngularJS service that implements the underlying event and state management mechanism for AngularJS attributes, directives, views and controllers.

Scope

Whereas, it's a conventional parameter name given to a directive's link function's first argument.

Q69. What technique uses Angular 2 for two way binding?
Answer

In general, two-way data binding in Angular 2 is the automatic synchronization of data between the view components and model. Two-way data binding allows the users to treat the model as a single source of truth in your application.

Q70. What are the life cycle hooks order in AngularJS?
Answer
This below mentioned will be the lifecycle hooks order in AngularJS.
  • ngOnChanges()
  • ngOnInit()
  • ngDoCheck()
  • ngAfterContentInit()
  • ngAfterContentChecked()
  • ngAfterViewInit()
  • ngAfterViewChecked()
  • ngOnDestroy()
Q71. What is the difference between ng-model and ng-bind in AngularJs?
Answer
Ng model Ng bind
This works as a two-way data binding where the user has to bind a variable to the field and output the same variable wherever the user desire to display that updated value anywhere in the application.
The syntax used for ng-model is –
<textarea ng-model="propertyName"></textarea>
It's a one-way data-binding used by developers for displaying the value inside HTML component as inner HTML.
The syntax used for ng-bind is –
<div ng-bind="propertyName"></div>
Q72. What is provider in Angular 2?
Answer

It's an object declared to Angular so that it can be injected within the constructor of user directives, components and other classes which are Angular instantiated.

Q73. What is zones in Angular 2?
Answer

It's an API or set of programs used by Angular 2 developers to update application view when any changes occurred. It's an execution context that situates across the asynchronous task.

Q74. What is pathMatch in angular routing?
Answer

Angular 2 applications require to redirect route and pathMatch is a property which informs a router how to match and map a URL to the path of an actual route. In the application, the router automatically select the route using component HeroListComponent only when the entire URL of matches for example-

const appRoutes: Routes = [
   { path: 'crisis-center', component: CrisisListComponent },
   { path: 'heroes', component: HeroListComponent },
   { path: '', redirectTo: '/heroes', pathMatch: 'full' },
   { path: '**', component: PageNotFoundComponent }
];

Q75. What is resolver in angular 2?
Answer

In actual, resolver (class) is a powerful technique which is used to achieve the best user experience when browsing between pages in the application. For the implementation of the resolver class, it is important to create a new folder called resolves. Thereafter put resolvers with same template resolveName.resolver.ts

Q76. What is Activatedroutesnapshot in angular 2?
Answer

Activatedroutesnapshot in Angular 2 is basically an immutable object which is used to represent a particular version of ActiveRoute.

For the implementation of Activatedroutesnapshot object following syntax can be used.

export class ActivatedRoute {
   /** The current snapshot of this route **/
   snapshot: ActivatedRouteSnapshot;
}

Q77. What is Router state in angular 2?
Answer

Router state represents all the state of the router as a tree of activated routes.

interface RouterState extends Tree {
   snapshot: RouterStateSnapshot
   toString(): string
}

Q78. What is the difference between lazy loading and eager loading in Angular 2?
Answer
Lazy loading Eager loadingIt
It needs to load using LoadChildren property in path or route configuration. This leading is useful for the growth of small size applications In order to load the eager loading module feature, it is important to import eager loading module into the application using imports metadata of decorator @NgModule
Q79. What is the use of arrow function in Angular 2?
Answer

They are additionally called lambda features in different languages. Using fats arrow (=>) we drop the want to use the 'function' keyword. Parameters are handed in the angular brackets <>, and the characteristic expression is enclosed inside the curly brackets {}.

items.forEach((a) => {
    console.log(a);
    incrementedItems.push(a+1);
});

Q80. What is the basic building block of Angular 2?
Answer
Here is the list of main building blocks of Angular 2:
  • Modules
  • Dependency injection
  • Data binding
  • Components
  • Templates
  • Directives
  • Metadata
  • Services
Q81. What is the significance of the catalyzer in Angular 2?
Answer

Codelyzer refers to an open-source tool that is used to run or detect if the predefined coding guidelines are followed or not. It only performs the static code analysis in angular 2 and typescript project because all platforms follow a set of easy and conventional coding to maintain it in a better way. Codelyzer also runs on the top of tslint where its coding convention is completely defined in the tslint.json file. The developer can also run it through an angular click.

Q82. If the path does not exist how will you redirect it or how you will deal with 404 in Angular 2?
Answer

Using the angular routing command it gets easier to navigate through the view page or any other file during any tasks. One can also configure the URL to redirect any other URL and this feature can also be handled to address the problem of "404 not found". By using the location services one can go back and forward along with the page history. Its syntax is- e can use {path: '/OUR_PATH', redirectTo: ['redirectPathName']}

This is one of the most common Angular 2 interview questions.

Q83. How will you deal with angular 2 application errors?
Answer

The applications in angular 2 have an error handling option which also includes the react JS library to use the catch function. In turn, the catch function includes a link that sends information about the error handler function. under this function one can send the error as a question to console file other instances will send it back in the main program to ensure the continuation of the operation of the main program. Once it is fixed whenever the error arises it will be redirected in the browser's console.

Q84. What are the difference between BrowserModule and platformBrowserDynamic in Angular 2?
Answer
Q85. What is gulp in Angular?
Answer

Gulp is a mission runner that approves you to define a sequence of repeatable tasks that can be run any time you need. You can automate boring matters like the minification and uglification of your javascript or some thing else you do in order to make your code production-ready.

Q86. What is HammerJS in Angular 2?
Answer

It is a famous library that helps you add aid for contact gestures (e.g. rotate, swipe, pan, zoom ) to your page. We will enhance a swipe-able card. Angular 2 presents a token known as HAMMER_GESTURE_CONFIG which accepts a HammerGestureConfig type.

How to install HammerJS

npm install hammerjs --save

Q87. What is the difference between submit and an ngSubmit event in Angular?
Answer

submit: It is an HTML default form submit an event, it will name the underlying technique when shape gets submitted.

ngSubmit: Is host binding located on the shape element. Basically, it prevents default submit event of browser(which can be structure post) with the aid of returning false. Eventually, you can prevent common PostBack calls or web page reload due to shape load. This way you can validate your form & submit it to the server by means of guide ajax from Component code

Q88. Explain app.module.ts file in Angular 2?
Answer
Q89. What is internationalization in angular?
Answer

With application users being across the globe nowadays, Internationalization in Angular is used to simplify the process of designing and preparing your app for multiple languages.

Q90. What is angular material design?
Answer

Angular Material Design is an open-source framework that can be used to build highly scalable mobile and commercial apps. There is no requirement of a license for usage. The main aim of Material Design is a unified version of visual, motion and interaction design over multiple devices.

Q91. What is angular UI?
Answer

To simplify the process of development in Angular 2, Angular UI is used which is a stack of modules written in Angular.js to provide more flexibility to the code. Having a wide variety of modules, you can use the UI for various declarations like components or pipes individually.

Q92. What is a metadata in Angular?
Answer

In Angular 2, Metadata is a way of processing a class and a component, MyComponent together as a class until specified by the user as a component.

Q93. What are filters in Angular 2?
Answer

A filter is a necessary phase of Angular 2 as well as Angular 4. It is basically used to filter an object from a crew of items, which are there in an array or an object array. It selects a subset of the objects from an array and returns it as a new array and displayed on UI. Filters can be used with an expression using pipe | sign. {{expression | filterName:parameter }} Angular 2 includes various filters to layout records of special fact types.

Q94. What is CDK in Angular 2?
Answer

The CDK, short for Component Dev Kit is a set of useful tools that help in implementing basic interaction patterns while neglecting their presentation. It represents a combination of core functionalities present in the Angular Material Library, excluding the styling specific Material Designs. The CDK is basically a platform with multiple functionalities to help in developing components.

Q95. What is Flex layout in Angular 2?
Answer

Flex Layout in Angular 2 is a component engine that allows you to create Flexbox page layouts with a fixed set of directives to use in designing templates. The Flex-Layout has made styling easy and user-friendly by having a TypeScript based Library, thus eliminating the need for external stylesheets/CSS Styling. In addition to this, it can be used along with Material Design for Design components and also providing intuitive breakpoints while development to aid in designing responsive layouts.

Q96. What is SPA in Angular 2?
Answer

SPA in Angular 2 stands for Single Page Applications. This is a type of web-application which fits into literally one page. All your code (JavaScript, HTML, CSS) is called using a single page load at multiple points by adding new data parallelly from the backend. Navigation between pages performed can be done without refreshing.

Q97. What is the best IDE for Angular 2?
Answer

An IDE’s main purpose is to provide a friendly coding environment. Angular 2 supports the following code-editors which are highly efficient:

  • Visual Studio Code
  • Sublime Text
  • Atom Editor
  • Webstorm
  • Angular IDE
  • ALM IDE
  • Brackets
  • Vim Editor
Q98. What is the difference between declarations and entryComponents?
Answer
Declarations entryComponents
Used to make Directives including components and pipes within a specific module Used to register components for offline computation in a module
Directives, components, and pipes are matched against the HTML only if they are declared or imported Components used for router config can be added implicitly
Q99. What is bundling in Angular 2?
Answer

In Angular 2, Bundling is known as the process of joining/combining multiple files into one single file. Third Party-libraries and other dependencies are generally bundled into a module for increasing productivity of code.

Q100. What is BASE HREF in Angular 2?
Answer

The <base href="/"> in Angular 2 is to direct the Angular Router to the static part of a URL. It helps the router to differentiate and make modifications to the URL accordingly.

Q101. What is use of subscribe in Angular 2?
Answer

The subscribe() function is observable in Angular 2 which defines how to obtain or generate values or messages to be published. To execute a particular observable in a timely fashion, you will have to create notifications using the subscribe() method.

Q102. What is the difference between imports declarations and providers?
Answer
Observables Declarations Providers
Ensures availability of exported declarations in different modules Ensures availability of different directives within a module Ensures the stable flow of services and values known to the Dependency Injection
Q103. What is entry component in Angular 2?
Answer

An entry component in Angular is one that loads imperatively, i.e it can be loaded without any referenced in the template, by any type or category. One can specify an entry component by either bootstrapping it as a NgModule or even in a routing definition.

Q104. Which decorator creates services in Angular 2?
Answer

The injectable decorator in Angular 2 allows the functionality of the creation of a service to be injected and used in AngularJS modules by defining it as a provider in the Component Decorator.

Following is a syntax to successfully create a service using the Injectable() decorator

import { Injectable } from '@angular/core';
import { Item } from './item';
import { ITEMS } from './mock-items';
@Injectable()
export class ItemService {
   selectedItems: Item[] = [];
   getItems(): Item[] {
   return ITEMS;
}
getSelectedItems(): Item[] {
   return this.selectedItems;
}
addItem(id:number): void {
   let item = ITEMS.find(ob => ob.id === id);
   if (this.selectedItems.indexOf(item) < 0) {
      this.selectedItems.push(item);
   }
}
removeItem(id:number): void {
   let item = this.selectedItems.find(ob => ob.id === id);
   let itemIndex = this.selectedItems.indexOf(item);
   this.selectedItems.splice(itemIndex, 1);
}

Q105. What is RouterOutlet in Angular 2?
Answer

In Angular 2, the RouterOutlet is a directive present in the router library to be used as a component. It marks the spot in a template for the router to display the components for that outlet.

Every outlet can have its unique name, which is determined by the optional name attribute. The name once set cannot be changed dynamically. If no value has been set, the default value is "primary".

<router-outlet></router-outlet>

<router-outlet name="left"></router-outlet>

<router-outlet name="right"></router-outlet>

The router outlet emits an activate event during the instantiation of a new component. When the component is destroyed, it is deactivated.

<router-outlet (activate)='onActivate($event)' (deactivate)='onDeactivate($event)'></router-outlet>

Q106. What is the purpose of using package.json in Angular?
Answer

In Angular, the package.json file lets you keep a track of dependencies within a project. By using the reference of these packages in the dependency section, it enables you to use a module bundler such as webpack, browserify, etc. The package.json also helps you to keep your project linked to the specific versions of each package if the new version introduces any changes.

Q107. What is ViewEncapsulation in Angular?
Answer

In Angular 2, View Encapsulation is used to define the template and style encapsulation variations available within a Component’s Component. In addition, it enables us to use Shadow DOM or maybe even emulate it as per requirements.

There are three view encapsulation types:
  • ViewEncapsulation.None - No Shadow DOM, hence, no style encapsulation.
  • ViewEncapsulation.Emulated - No Shadow DOM but emulated style encapsulation.
  • ViewEncapsulation.Native - Proper Native Shadow DOM.

@Component({
selector: 'my-app',
template: `
<h1>Hello World!</h1>
Shadow DOM Rocks!
`,
styles: [`
:host {
display: block;
border: 1px solid black;
}
h1 {
color: blue;
}
.red {
background-color: red;
}
`],
encapsulation: ViewEncapsulation.ShadowDom
})
class MyApp {
}

Q108. What is ECMAScript in Angular 2?
Answer
ECMAScript is a standard of coding, implemented by Javascript. In some browsers, Javascript implements Ecmascript 2015 standards(also called ES6). It is basically the JavaScript that browsers understand.
Q109. When rendering the page for the first time in Angular, which page is called first?
Answer

In Angular, the main.ts is the entry point of the application, which runs first when you render a page in Angular. It compiles the application with JIT and bootstraps the Angular application. In Angular 2, you can bootstrap multiple environments to import a module specific to the environment during which angular looks for a specific module to run first.

Q110. What is RxJS in Angular?
Answer

In Angular, Reactive Extensions for the JavaScript (RxJS) is a reactive stream library that allows you to work with asynchronous data streams in Angular 2. RxJS can be used in the browser or on the server-side while using Node.js.

Here’s a simple example of integrating the rx.angular.js, a dedicated library for maintaining excellent inoperability between RxJS and Angular 2. Basically, we are taking a $watch expression and turning it into an observable.

// View

<input type="text" ng-model="search" />
 

// Controller
observeOnScope($scope, 'search')
.throttle(1000)
.map(function(change){
return change.newValue || "";
})
.distinctUntilChanged()
.flatMapLatest(searchWikipedia)
.safeApply($scope, function(result) {
$scope.data = result;
})
.subscribe();

Now, this will make changes to $scope.search and emit the following user types:
{
oldValue: "asyn",
newValue: "async"
}

Q111. What is the difference between property binding and event binding?
Answer
Property binding

When you have to pass the value from a parent component in ANgular to a child component, we have to use the property binding meaning that by doing so we are sending the value using the attribute on a component and thereby get the parent using the @Input annotation for the example of property binding like the below example: <my-child [myProp]="prop" />

Event Binding

Caching of Child’s Event/Method using the parent component.

This is used when we have to fire some event on click or maybe something else from the child component while passing it to the Parent.

Here’s an example:

<my-child [myProp]="prop" (onPropChange)="onPropChange($event)"</strong> /> Here, we have user onPropChange as event binding to catch and fire an event using EventEmitter.

Q112. What is string interpolation Angular?
Answer

String Interpolation is a special syntax in Angular 2 which is a more efficient alternative to property binding. It is used to display dynamic data on an HTML template while facilitating you to make changes on the component.ts file and fetch data for the HTML template.

Below is an example of a String Interpolation syntax. It should be between double curly braces {{ }} and hence also called a moustache syntax:

class AppComponent
{
    propertyName: string;
    object: DomainObject;
}
{{ propertyName }}
{{ object.propertyName }}