Angular 2 Interview Questions and Answers | 61 Top Angular 2 Questions

Top 61 Angular 2 Questions and Answers for Job Interview :

1. What is Angular 2?

Answer : Angular 2 is a framework that is used to do build large-scale and high-performance web application. Any application developed using the Angular 2 framework becomes very easy to test because of the concept of modularization.

2. What are the features of the Angular 2?

Answer : The Angular 2 has a number of features:

TypeScript: − The current version of Angular, i.e., Angular 2 is based on the concept of TypeScript. It is a superset of JavaScript and is maintained by Microsoft.

Services: − Services are a set of code that can be shared by different components of an application. Say, there is a data component that has picked data from a database, then that can be used as a shared service that can be used across multiple applications.

Components: − The earlier version of Angular had a focus on the concept of controllers. However, it has changed the focus now to the concept of components as compared to controllers. Components are used to build applications using modularity and dividing the complete program into a number of modules. This helps in maintaining the application in a better way over a period of time and helps in the long run.

3. Mention the main components of Angular 2.

Answer : Angular 2 has the given components: −

Component – This feature is used to bring the various modules of the application together.
Service: − This feature is used to create components which can be shared across the entire application.
Modules: − This feature is used to break up the application into logical pieces of code or what is commonly known as a module. Each piece of code is designed to perform a single task. This helps in the process of development.
Templates: − This feature is used to define the views of an Angular JS application.
Metadata: − This feature is used to add more data to an Angular JS class.

4. What do you know about the tsconfig.json file?

Answer : The tsconfig.json file is used to provide a number of options about the  Typescript used for any Angular JS project while working on Angular 2. Observe the following code to understand the usage of this file:

{
“compilerOptions”: {
“target”: “es5”,
“module”: “commonjstest”,
“moduleResolution”: “node”,
“sourceMap”: true,
“emitDecoratorMetadata”: true,
“experimentalDecorators”: true,
“lib”: [ “es2017”, “demo” ],
“noImplicitAny”: true,
“suppressImplicitAnyIndexErrors”: true
}
}

5. What are the default codes provided in the app.module.ts file?

Answer : Observe the given piece of code to know more about the code line that are present by default in the app.module.ts file:

import { BrowserModule } from ‘@angular/platform-browser’;
import { NgModule } from ‘@angular/core’;
import { AppComponent } from ‘./app.component’;
@NgModule({
imports: [ BrowserModule ],
declarations: [ AppComponent ],
bootstrap: [ AppComponent ] })
export class AppModule { }

The import statement in the first line has been used to import the functionality from existing modules. The first 3 statements have been used to import the BrowserModule, the NgModule and the AppComponent modules into the file. The NgModule is a decorator module that is used to define the imports, declarations, and bootstrapping options in the future. The BrowserModule is required by default for development of any web-based Angular application.
The bootstrap option tells the Angular about the Component that has to be bootstrapped into the application.

6. How does the user convert the input to lowercase or uppercase?

Answer : The input in any Angular application can be easily converted to lowercase or uppercase by using a lowercase and uppercase filter. Observe the given example where a lowercase as well as an uppercase filter has been added to an expression using the pipe character.

<div>
This Tutorial is {{Demo Tutorial}}

The first Topic is {{appList[0] | lowercase}}

The second Topic is {{appList[1] | uppercase}}

</div>

7. What do you mean by Template in Angular 2?

Answer : A template is used to define a view in Angular 2. By default, Angular 2 provides the user a template to define the views of any web application that is being developed.

8. How is string converted to percentile in Angular 2?

Answer : The new version of Angular has been provided with a number of filters to perform many tasks.

The percentile filter is provided to convert a string into percentile.

9. Why are decorators used in Angular 2?

Answer : Decorators are an integral part of Angular 2 as thay are used to identify the different classes and the type of the object that have been created by typescript.

10. What do you know about the host decorator in Angular 2?

Answer : The host decorator is an in-built feature of Angular 2 that is generally used to bind the properties of the components with the values of the UI elements. These properties are clearly defined within the @HostBinding annotation inside the component class.

11. What do you know about Pipes in Angular 2?

Answer : Pipes is one of the commonly used features of Angular 2. They are used in templates to convert any content into the desired output or according to the business requirement.
The general symbol for a pipe is like this “|”

For example – {{appList[0] | lowercase}}.

12. Mention the features that have been added to the new version of Angular.

Answer : The new version of Angular has been developed using Typescript and fulfils all criteria of the ECMA specifications. The following new features have been added to Angular 2:

  • Directives- The specification for directives has been considerably simplified. However, they are still subject to change. With the @Directive annotation, a directive can be declared.
  • Dependency Injection- There has been provisions made for improved dependency injection model in Angular2 due to which there are more opportunities for component / object-based work.
  • Component-Based- Angular 2 has been designed to be component based. The controllers and the $scope are no longer used. They have been replaced by components and directives.
  • Generics- TypeScript has generics which can be used in the frontend development.
  • Lambdas with TypeScript- In TypeScript, lambdas are available which have been finally included in Angular 2.
  • Use of TypeScript- TypeScript is a super set of JavaScript which has been built and maintained by Microsoft and has been chosen by the AngularJS team for development. The presence of the types makes the code written in TypeScript less susceptible to to run-time errors. In recent times, the support for ES6 has been improved considerably and only a few features from the ES7 have been added.
  • Forms and Validations- Forms and validations are an important aspect of frontend development. Within the Angular 2, the Form Builder and Control Group have been newly defined to include the concept of forms and validations.

13. Why does a user require Angular 2?

Answer : Angular 2 is not just an upgrade from Angular but a totally new development application that is built specifically for frontend developers. The entire framework has been rewritten from scratch. Angular 2 has got rid of a number of things like the $scope, the controllers, the DDO, the jqLite, the angular.module file and many such outdated aspects.

It uses components for almost everything. Imagine that even the whole app is now a component. Also it takes advantage of ES6 / TypeScript syntax. Developing Angular 2 apps in TypeScript has made it even more powerful.

Apart from that, many things have evolved and re-designed like the template engine and many more.

14. Define TypeScript.

Answer : TypeScript is a super set of JavaScript that has been completely typed which has been built and maintained by Microsoft and chosen by the AngularJS team for development.

15. Why does Angular 2 require the Typescript?

Answer : JavaScript is the most popular language for developing web application UI. For many application developers, especially front end developers, having exposure in languages like Java and C#, creating the front end of a Web application in JavaScript is a very unwieldly process. So TypeScript provides the following advantages over JavaScript-

  • Usage of the object-oriented programming paradigms and techniques-  There is a lack of object-oriented design paradigms and techniques in JavaScript. However, this is not the case in TypeScript. It makes use of Objected Oriented features like Polymorphism, Inheritance etc.
  • Structure the code- There are a number of different coding styles for JavaScript. This feature leads to an unstructured code. However, with TypeScript, the user can create structured code.
  • Standard coding guidelines- There is no type checking in JavaScript. The code style needs to be defined and this is a hard to enforce style guide. TypeScript has been designed to overcome this issue with features like Code Analysis and Navigation, Documentation, Intellisense etc.

16. Provide a piece of code to show how using JavaScript is a tough language to use for front end developers and how TypeScript can solve it.

Answer : Consider this example where the user wants to create a class Employee in JavaScript. There is no class keyword in JavaScript so the given code has to be executed –

<html>
<head>
</head>
<body>
<script>
function Employee()
{
this.name=””;
this.id=””;
this.Validate=function()
{
alert(“Validate”);
}
}
</script>
</body>
</html>
Same can be written using TypeScript as follows-

class Employee
{
public name : string = “”;
public id : string = “”;
Validate()
{
alert(“validate”);
}
}

This Customer.ts will compile to the above JavaScript code.

17. What do you mean by Ecmascript?

Answer : ECMAScript is a subset of JavaScript. Angular2 supports ES6 and higher versions. JavaScript can be safely described as ECMAScript at the core but with additional features provided by the developers. Languages such as ActionScript, JavaScript, and JScript use ECMAScript at its core. As a comparison, the AS/JS/JScript can be considered as 3 different cars, but all of them use the same engine. Each of this car’s exterior is different though, and there have been several modifications made to each of the car to make it unique.

18. What does the @ngmodule annotation do?

Answer : The @NgModule annotation is a decorator function.

A decorator function in Angular 2 allows the users to mark something as an entity of Angular 2. It could be a module or a component or anything else and it enables the user to provide additional data. This feature determines how this particular Angular 2 entity will be processed, instantiated and used at runtime. So, whenever the user writes the @NgModule annotation, the user is indirectly telling the Angular 2 module about what is going to be included and used in the module.

19. What is a Traceur Compiler in Angular 2?

Answer : The Traceur Compiler is a JavaScript.next-to-JavaScript-of-today compiler that allows the user to use the features from the future today. The Traceur Compiler supports the ES6 as well as some of the experimental ES.next features. The Traceur Compiler’s goal is to inform the design of the new JavaScript features which are only valuable if they allow the user to write some better code.

20. What do you mean by Component in Angularjs 2?

Answer : In Angular 2, a Component can be defined as a special kind of directive that uses a simpler configuration which is suitable for a component-based application structure only.

21. What does the @inputs annotation do in Angular 2?

Answer : In Angular 2, the @Input annotation allows the user to pass data into the controller and templates through HTML and is used for defining the custom properties. This allows the user to easily reuse components and use them to display different values for each instance of the renderer.

22. What is the function of the @outputs annotation in Angular 2?

Answer : Components push out events using a combination of the @Output annotation and an EventEmitter. This creates a clean separation between the reusable Components and the application logic.

23. What is the PrimeNG? How can a user use the PrimeNG in Angular 2?

Answer : The PrimeNG is a collection of rich UI components used for Angular 2. The PrimeNG can be considered as a counterpart of the popular JavaServer Faces Component Suite, and PrimeFaces. All widgets are open source and are free to use under the Apache License 2.0 which is a commercial-friendly license. The PrimeNG has been developed by the PrimeTek Informatics, a company which has years of expertise in the developing open source UI components. The AngularJS makes it possible to use the predefined components for the development of structures such as tables etc. This feature helps developers to save both time and efforts. By using the PrimeNG, front end developers can be used to create highly functional and interactive applications in no time.

24. Mention some features about Components in Angular 2.

Answe : The Components have the following features in Angular 2:

  • For register component the users need to utilize the @Component annotation the meta-data annotation.
  • The Component is a directive which uses the shadow DOM to create and encapsulate visual behavior commonly known as components. The Components are typically used to create UI widgets.
  • A component is used to break up the application into smaller components.
  • Only one component can be present per DOM element.
  • The @View annotation is a decorator or templateurl template and is mandatory in the component.

25. Mention some features about Directives in Angular 2.

Answer : The Directives have the following features in Angular 2:

  • For register directives we use the @Directive meta-data annotation.
  • Directives are used to add behavior to an existing DOM element.
  • A Directive is used to design all kinds of re-usable components.
  • Many directives can be used in a single DOM element, unlike Components.
  • Directives don’t need the usage of the @View annotation.

26. What is the use of Angular 2 when the Angular already existed?

Answer : The Angular 2 has the following advantages which make it more useful than Angular:

  • It has faster change detection.
  • It has faster initial loads.
  • Angular 2 is a modern application.
  • The developers have improved the rendering times.
  • It leverages web component technologies for building reusable user interface widgets.
  • Angular 2 takes advantage of the features provided in the latest JavaScript standards and features beyond such as classes, modules, and decorators.
  • The Angular 2 has fewer built-in directives to learn simpler binding.
  • It supports both the Greenfield and the Legacy browsers- Edge, Chrome, Firefox and Internet Explorer back to IE9.
  • Angular 2 enhances the user’s productivity to improve the day-to-day workflow.

27. What is special about an Angular 2 Component?

Answer : Each component in the Angular 2 comprises a template, which is the HTML equivalent for the user interface. When the user adds a class to this template for the code associated with a view. The class contains the properties as well as the methods which perform actions for the view. A component also has metadata which provides additional information about the component to Angular 2 for further manipulation.

28. Mention the languages that can be used to build an Angular 2 application.

Answer : The languages EcmaScript or ES is usually used to build an Angular Appplication. The ES 3 is supported by older browsers which is a big advantage. The ES 5 is the version that is currently supported by most modern browsers. The ES 6 specification has been recently approved and has been renamed ES 2015. Most browsers don’t yet support ES 2015.

29. How to set up the Develop Environment for Angular 2?

Answer : In order to set up the development environment for any Angular 2 application requires the user to follow just two basic steps:

  • First the Node Package Manager or the NPM has to be installed.
  • Next, the Angular 2 application has to be set up.

30. What do you mean by NPM?

Answer : The NPM or the Node Package Manager is a command line utility that is used to interact with a repository of open source projects. It usually becomes the package manager for JavaScript. By using the NPM the user can install libraries, packages, and applications, along with their dependencies.

31. Mention the steps to set up an Angular 2 Application.

Answer : The following steps need to be followed to set up any Angular 2 Application:

  • Create an application folder.
  • Create the tsconfig file in order to configure the TypeScript compiler.
  • Create the package.json file in order to define the libraries and the scripts the user needs.
  • Create the typings.json file which is used to specify a missing TypeScript type in the definition file.
  • Install the libraries and typing files.
  • Create the host Web page which is generally the index.html.
  • Create the main.ts file which is the final step. It is used to bootstrap the Angular 2 Application with the root component.

32. What are the probable security threats that need to be dealt with when working with an Angular 2 application?

Answer : Similar to other client side or web applications, when working with the Angular 2 Application, one should also follow some of the basic guidelines to mitigate the security risks. Some of these risks are:

  • Avoiding the usage or the process of injecting the dynamic HTML content to the user’s component.
  • If the user is using an external HTML that is coming from a certain database or is somewhere outside the application it needs to be sanitized.
  • The user must try not to put external URLs in the application unless all those URLs are trusted. The user must avoid an URL re-direction unless it is a trusted source.
  • The user must also consider using the AOT compilation or offline compilation.
  • The user must try to prevent the XSRF attack by restricting the API and the usage of the app for trusted or secure environment/browsers.

33. Mention the advantages of Angular 2 over Angular 1.

Answer : The Angular 2 has the following advantages over the Angular 1:

  • It has simpler Dependency Injection.
  • It has better Speed and Performance. There is no $Scope in Angular 2.
  • It has the additional benefits of ES6 and Typescript.
  • It is a modular and a cross platform.
  • It is definitely easier to learn.
  • It has flexible Routing with Lazy Loading Features.

34. Mention how routing works with Angular 2.

Answer : Routing is a mechanism which enables a user to navigate between views and components. Angular 2 simplifies the routing process and provides flexibility to configure and define at module level by using the concept of Lazy loading.

The Angular 2 application has a single instance of the Router service and whenever the URL changes, the corresponding Route is matched from the routing configuration array. On a successful match, it applies the redirect function and the router builds a tree of the ActivatedRoute objects and contains the current state of the router. Before redirection, the router will check whether a new state is permitted by the running Guards by suing the CanActivate method. The Route Guards is simply an interface method that the router runs to check the route authorization. After the Guard runs, it will resolve the route data and activate the router state by the process of instantiation of the required components into the <router-outlet> </router-outlet>.

35. What do you know about Event Emitters?

Answer : The Angular 2 application doesn’t have a bi-directional digest cycle unlike Angular 1. In Angular 2 any change that has occurred in the component always gets spread from the current component to all its children in the hierarchy. If the change from one component needs to be reflected in any of its parent component in hierarchy, the user can emit the event by using the Event Emitter API. The EventEmitter is a class defined in @angular/core module which can be used by components and directives to emit the custom events.

36. How do the Event Emitters work in Angular 2?

Answer : Observe the following code:

@output() somethingChanged = new EventEmitter();

The user has used the somethingChanged.emit(value) method to emit the event. This is usually done in setter when the value is being changed in the class. This process of an event emit can be subscribed by any component of the module by using the subscribe method.

myObj.somethingChanged.subscribe(val) => this.myLocalMethod(val));

37. Why is a Codelyzer used in an Angular 2 application?

Answer : All enterprise applications follow a set of coding conventions and guidelines to maintain the code written in an application in a better way. The Codelyzer is an open source tool that is used to run and check whether the pre-defined coding guidelines have been followed. The Codelyzer, however, only performs static code analysis for Angular and Typescript project. The Codelyzer runs on top of the tslint file and its coding conventions are usually defined in the tslint.json file. The Codelyzer can be run via angular CLI (Command Line Interface) or the NPM directly. Certain code editors like the Visual Studio Code and Atom also support the Codelyzer. This can be achieved by changing certain basic settings.

38. Mention the steps/code to set up the Codelyzer in the Visual Studio Code.

Answer : In order to set up the Codelyzer in the Visual Studio code, the user needs to go to File -> Preferences -> User Settings and then the path has to be added for the tslint rules.

Hide   Copy Code

{
“tslint.rulesDirectory”: “./node_modules/codelyzer”,
“typescript.tsdk”: “node_modules/typescript/lib”
}
To run from CLI, the user needs to use the ng lint.
To run from NPM, the user needs to use the npm run lint

39. How can the Angular 2 be optimized for better performance?

Answer : Optimization depends on the type and the size of the application and many other additional factors. However, the following points must be considered by the user while optimizing the Angular 2 application:

  • Consider the AOT compilation.
  • The user needs to make sure the application is bundled, uglified, and the tree shaking is done.
  • The user also needs to make sure that the application doesn’t have un-necessary import statements.
  • The user must also ensure that any 3rd party library, which has not been used in the application, has been removed from the application.
  • The application must have all the dependencies and the dev-dependencies clearly separated from each other.
  • Lazy loading can also be considered instead of a fully bundled app if the app size is more.

40. How to define custom typings in Agular 2 in order to avoid warnings from the editor?

Answer : In Angular 2, the 3rd party library comes with its own .d.ts file for its type definition. In some cases, the user needs to extend the existing type by providing some more properties to it or if the user needs to define additional types to avoid Typescript warning.

If the user needs to extend the type definition for an external library, as a good practice, the node_modules or existing typings folder must be left untouched. A new folder can be created, for example Custom Typings, and keep all the customized type definition in that. To define the typings for application (JavaScript/Typescript) objects, the user needs to define the interfaces and entity classes in the models folder in the respective modules of the application. For such typical cases, the user can define or extend the types by creating their very own “.d.ts” file.

41. What is the Shadow Dom?

Answer : The Shadow DOM is a part of the HTML spec which allows the developers to encapsulate their HTML markup, CSS styles and JavaScript. The Shadow DOM, along with a few other technologies, gives all kinds of developers the ability to build their own 1st class tags, web components and APIs just like the <audio> tag. These new tags and APIs are collectively referred to as Web Components.

42. How does the Shadow Dom help the Angular 2 to perform better?

Answer : The Shadow DOM provides a better separation of concern along with lesser conflict of styles and scripts with other HTML DOM elements. Since the Shadow DOM is static in nature, it is an excellent candidate to be cached as it is not accessible to developer. The cached DOM can thus, be easily rendered faster in the browser providing better performance. The Shadow DOM can be managed comparatively pretty nicely while detecting the change in any Angular 2 application and re-paint of then view can then be managed efficiently.

43. What do you know about the AOT Compilation?

Answer : The AOT compilation is an acronym for Ahead Of Time compilation. In this process, the in-built Angular compiler compiles the Angular components and templates to the native JavaScript and HTML script during the build time. The compiled HTML and JavaScript script is then deployed to the web server so that the compilation as well as the render time can be saved by the browser.

44. Mention the advantages of AOT Compilation.

Answer : AOT Compilation has the following advantages:

  • AOT has fewer number of HTTP Requests: If the app built with Angular 2 is not bundled to support Lazy Loading, for each associated HTML and CSS script, a separate request is specifically sent to the server. The pre-compiled application in-lines all the templates and styles with components and hence, the number of HTTP requests to the server would be lesser.
  • Faster download: Since the application is already compiled, many of the Angular compiler related libraries are not required to be bundled and hence, the app bundle size gets reduced. Thus, the application can be downloaded faster.
  • Detect error at build time: Since compilation is carried out beforehand, many compile time errors can be detected which provides a better degree of stability of application.
  • Faster Rendering: If the application is not AOT compiled, the compilation process happens in the browser once the application is fully loaded. This has a wait time for all necessary components to be downloaded, and then the time taken by the compiler to compile the application. With an AOT compilation, this is optimized.

45. Mention the disadvantages of an AOT Compilation.

Answer : The following are the disadvantages of an AOT Compilation:

  • It works only with HTML and CSS while other file types need a previous build step.
  • It has no watch mode and hence, must be done manually by using the bin/ngc-watch.js which finally compiles all the files.
  • It needs to maintain an AOT version of bootstrap file which might not be required while using tools like CLI.
  • It needs a cleanup step before compiling.

46. Mention the differences between Promises and Observables.

Answer :

 Promises:

  • It returns a single value.
  • It is not cancellable.

Observables:

  • These work with multiple values over time.
  • They are cancellable, unlike promises.
  • They support map, filter, reduce and similar operators.
  • They are one of the proposed features for ES 2016.
  • They use Reactive Extensions (RxJS).
  • They utilize an array whose items arrive asynchronously over time.

47. Differentiate between a Constructor and a Ngoninit.

Answer :

 Constructors:-

  • The constructor is a default method that runs when a component is being constructed.
  • The constructor is a Typescript feature and it is used only for a class instantiations and nothing to do with Angular 2.
  • The constructor is called first time before the ngOnInit().

ngOnInit:-

  • The ngOnInit event is an Angular 2 life-cycle event method that is called after the first ngOnChanges and the ngOnInit method is used to parameters defined with the @Input annotation otherwise the constructor is OK.
  • The ngOnInit is called after the constructor and the ngOnInit is called after the first ngOnChanges.
  • The ngOnChanges is called when an input or output binding value changes.

48. Mention some Component-specific hooks.

Answer : The following are the specific Component-specific hooks:

ngAfterContentInit: This is the Component content that has been initialized.

ngAfterContentChecked: After the Angular checks the bindings of the external content that it projected into its view, this Component is used.

ngAfterViewInit: After the Angular creates the component’s view, this is used.

ngAfterViewChecked: After the Angular checks the bindings of the component’s view, this is used.

49. What are the life cycle hooks of an Angular 2 application?

Answer : The Angular 2 component/directive has lifecycle events that are managed by the @angular/core annotation. It creates the component, renders it, creates and renders its children, processes changes when its data-bound properties change, and finally destroys it before removing its template from the DOM. Angular 2 provides a set of lifecycle hooks or special events which can be tapped into this lifecycle and perform operations when required. The constructor is executed prior to all lifecycle events. Each interface has a single hook method prefixed with ng.

50. Mention some events that are applicable for both component/directives in Angular 2.

Answer : Here is a list of some of the events that are applicable for both the component/directives while few are specific to components:

  • ngOnInit: This event initializes the component/directive after the first ngOnChange triggers. This is the most frequently used method to retrieve the data for the template from a back-end service.
  • ngOnChanges: This event responds when the Angular sets its data-bound property which receives the current and previous object values.
  • ngOnDestroy: This event is used to cleanup just before Angular destroys the directive/component. The user needs to unsubscribe observables and detach event handlers to avoid memory leaks.
  • ngDoCheck: This event is used to detect and act upon changes occurring outside Angular context. It is called by the user only when every change detection run.

51. What do you mean by Lazy Loading?

Answer : Most of the enterprise applications contains various modules for specific business cases. Bundling a complete application code and loading it becomes a huge performance impact at initial call. Lazy loading enables the user to load only the module that the user is interacting with and keep the rest to be loaded at runtime on demand. Lazy loading speeds up the application initial load time by splitting the code into multiple bundles and loading them on demand. Every Angular application must have one main module say AppModule. The code should be split into various child modules such as NgModule based on the application business case.

52. How can the user enable Lazy Loading in Angular 2?

Answer : The following steps need to be followed to enable Lazy loading in Angular 2:

  1. The user doesn’t require to import or declare lazily loading module in root module.
  2. The route needs to be added to top level routing (app.routing.ts) and set loadChildren. The loadChildren takes the absolute path from the root folder followed by #{ModuleName}. The RouterModule.forRoot() takes routes array and configures the router.
  3. Next, import a module specific routing in the child module.
  4. In the child module routing, the path is specified as an empty string ‘ ‘, the empty path. The RouterModule.forChild again takes the routes array for the child module components to load and configure router for child.
  5. Finally export the const routing: ModuleWithProviders = RouterModule.forChild(routes);

53. What do you know about local reference variables, ViewChild and ContentChild?

Answer : The Local template variables in Angular 2 is generally used to refer to the HTML elements and use their properties to access the concerned siblings or children.

Let’s consider an example where an input field named username is required:

<input type=”text” required … />

This HTMLInputField can be made available to the template using the ‘#’ symbol with a variable name saying username.

<input type=”text” #username required … />

Now, this HTMLInputElement can be accessed from anywhere in the current template. Checking validation and showing appropriate message based on the validation rule can be considered an example. However, username HTML reference is not accessible in the component/directive.

To access this in the component, Angular 2 provides the @ViewChild decorator which accepts the local reference variable.

@ViewChild(‘username’) username: HTMLInputElement;

A ViewChild element can be read after the view is initialized (ngAfterViewInit).

A ContentChild is used to query the reference of the DOM within ng-content. Content Child are set before the ngAfterContentInit lifecycle hook.

54. How to get a substring from a string?

Answer : The slice filter is used to slice a piece of data from the input string. In the given example, a slice filter has to be added to an expression using the pipe character. Here the property value is sliced based on the start and end positions.

<div>

The name of this Tutorial is {{TutorialName}}
The first Topic is {{appList[0] | slice:1:2}}
The second Topic is {{appList[1] | slice:1:3}}
The third Topic is {{appList[2]| slice:2:3}}
</div>

55. How is a string converted to a date?

Answer : The date filter is used to convert the input string to date format. In the given example, a date filter has been added to an expression using the pipe character. Here the property value is converted to date format.

<div>

The date of this Tutorial is {{newdate | date:”MM/dd/yy”}}
</div>

56. How can a user convert a string into currency?

Answer : The currency filter is used to convert the input string to currency format. In the given example, a currency filter has been added to an expression using the pipe character. Here the property value will be converted to currency format.

<div>

The currency of this Tutorial is {{newValue | currency}}

</div>

57. How is a string converted into a percentage?

Answer : The percent filter is used to convert the input string to percentage format. In the given example, a percent filter has been added to an expression using pipe character. Here property value will be converted to percentage format.

<div>

The percentage of this Tutorial is {{newValue | percent}}
</div>

58. Differentiate between ActivatedRoute and RouterState.

Answer : We have compiled a list of the differences between the RouterState and the ActivatedRoute:-

  1. The ActivatedRouteSnapshot has old data. Whenever the route changes, the ActivateRouteSnapshot has data from previous route whereas the RouterState cares about application components and to be more specific, about their arrangements.
  2. The ActivatedRoute consists of the information about a route associated with a component loaded in an outlet whereas the RouterState represents the state in which the writer actually is.
  3. The ActivatedRouteSnapchat is required to traverse all the activated routes whereas during a navigation, after all forms of redirects have been applied, the router creates a RouterStateSnapshot.

59. What is meant by a shared module in Angular 2?

Answer : The Shared module is used to import the services in both eager and lazy loaded module. Lazy loaded modules create their own branch on the dependency injection tree. Shared module, on the other hand, consists of the services that are registered by the angular in the root app injector. For this, the user does not need to import it in the lazy module because lazy loaded modules already have access to the services defined at the root. Components, pipes and directives have also been defined in the shared module. Other modules that import the shared module can use it in their templates. This means that the modules can be imported normally in the lazy loaded module. The shared module contains the code that will be used across the applications and featured modules. It also consists of the common template components. “Dumb components” should also be present in the shared module. It consists of some common angular modules too. When the user is importing the shared module, he/she will also need to import the module with its providers, because there is no app module in the test.

60. What is a Structural Directive in Angular 2?

Answer : Structural directives are used to manipulate the DOM in angular. Structural directives are responsible for HTML layout. By adding, removing, or manipulating all LMNs in Angular, they shape or reshape the structure of DOM. This structural directive is applied to a host element with the help of other directives. The directives then do whatever they are supposed to do with that host element and its descendants. Structural directives can be easily recognized. It can also delay the instantiation of a component or an element. It can also be used for cosmetic effect or manually handling the timing of the loading of components. Structural directives are bound to a template. The two most common structural directives are “ngIf” and “ngFor”. The process occurring in a structural directive is dynamic.

61. What are the modern browsers that are supported by Angular 2?

Answer : Angular supports most of the recent browsers some of which are:

  • Google Chrome
  • Firefox
  • Edge
  • IE for versions 9-11
  • Safari
  • iOS 7.1
  • Android 4.1
  • IE Mobile

 

Conclusion:

Angular has made significant impact in the market as more and more companies adopt digital technologies. Angular technology has become one of the most preferred technologies by many companies for their digital transformation programs. We tried to provide you the best 61 Angular 2 Interview questions to help you in Job interview.

Kiara is a career consultant focused on helping professionals get into job positions in the tech industry. She is also a skilled copywriter who has created well-crafted content for a wide range of online publications in the career and education industry.