Angular 2 Interview Questions And Answers

1. What is the need of Angular2?
Answer: Angular 2 is not just a typical upgrade but a totally new development. The whole framework is rewritten from the ground. Angular 2 got rid of many things like $scope, controllers, DDO, quite, angular. module etc. 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. (angular 2 interview questions)

2. What are the key components of Angular 2?
Answer: Angular 2 has components like Modules, Component, Templates, Metadata, and Service.
The Angular 2 Component combines the AngularJS Directive, Controller, and Scope.
Components are the fundamental building blocks of Angular applications.
They display data on the screen, listen for user input, and take action based on that input.

3. What is a DOM in Angular 2?
Answer: DOM stands for Document Object Model. Angular 2 directives are used to bind application data to the attributes of HTML DOM elements.

4. What are Event Emitters and how it works in Angular 2?
Answer: Angular 2 doesn’t have bi-directional digest cycle, unlike angular 1. In angular 2, any change occurred in the component always gets propagated 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, we can emit the event by using the Event Emitter API.

In short, EventEmitter is class defined in @angular/core module which can be used by components and directives to emit custom events.
We use something changed.emit(value) method to emit the event. This is usually done in setter when the value is being changed in the class.

This event emit can be subscribed by any component of the module by using subscribe method.

5. How Would You Optimize The Angular 2 Application For Better Performance?
Answer: Well, optimization depends on the type and size of the application and many other factors. But in general, I would consider the following points while optimizing the angular 2 apps:

Consider the AOT compilation.
Make sure the application is bundled, uglified, and tree shaking is done.
Make sure the application doesn’t have un-necessary import statements.
Make sure that any 3rd party library, which is not used, is removed from the application. (Online Training Institute)
Have all dependencies and dev-dependencies are clearly separated.
I would consider lazy loading instead of fully bundled app if the app size is more.

6. What is Angular 2?
Answer: Angular 2 is a completely revived component-based Javascript framework in which an application is a tree of loosely coupled components. It is a more advanced version of angularJS. It is more of an “all in one” framework so it also helps in creating a single website without getting trapped into different JS frameworks. An Angular 2 is a modular framework in which our code is divided into individual procedures that offer a similar kind of functionality, hence improving the testing, up-gradation and maintenance of the application. It has a lot of useful features such as- server-side rendering, cross-platform, and supports more languages than any other framework. It is a new typescript framework built around the concept of components which is paving the way for better and spacious development. We can even make hybrid applications using Angular 2 which gives us a sharp edge by providing us the flexibility to use the same standard codes for developing other applications. 

7. What are Event emitters?
Answer: An Event emitter is a class defined in a core module that can be used by components and directives to emit custom events.

8. How to cache an observable data in Angular 2?
Answer: Caching of an observable data is done with the help of “observable.cache”. We can use caching in order to cache the response in the memory and then, on the next subscription, instead of requesting the remote server again. This operator is used at the end of the string. Caching is important for the performance, especially on bandwidth restricted devices and slow networks. You should have a good understanding of caching while working with promises but while translating it to observable, it is a bit difficult. Therefore, when interacting with observables, we typically set up a subscription on the consumer side and react to values coming through the pipe. We can easily add caching to the observables by adding publishReplay(1) and refCount.

9. Why are decorators used in Angular 2?
Answer: 
An Event emitter is a class defined in a core module that can be used by components and directives to emit custom events.

10. What would you have in a shared module in Angular 2?
Answer: Shared module is used to import the services in both eager and lazy loaded module. We all know that lazy-loaded modules create their own branch on the dependency injection tree. The shared module consists of the services that are registered by the angular in the root app injector. For this, we need not import it in the lazy module because lazy loaded modules already have access to the services defined at the root. Components, pipes, and directives are also 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 typically consists of some common angular modules too. When you are importing the shared module, you will also need to import the module with its providers, because there is no app module in the test. (Company)

11. How do you define the transition between two states in angular?
Answer: Transitions between two states take place so that we can build simple animations between two states driven by a model attribute. Transition basically means navigating from the current state to a new state. In angular, the transition is an animation-specific function which is used in angular’s animation DSL language. Transition declares the sequence of animation steps that will be executed when the entered value is satisfied. A function is provided an argument for a transition and it will be executed each time a state change occurs. In this, if the function is true, then the animation will run else it won’t get executed.
These animation transitions are placed within the animation triggers. The transition depends upon what the animation was in the previous state and what it will become in the next state. In other words, if a transition is defined that matches the old/current state criteria then the associated animation will be triggered.

12. What are the core differences between Observables and Promises?
Answer: A nice answer taken from stack overflow:
A Promise handles a single event when an async operation completes or fails.
Note: There are Promise libraries out there that support cancellation, but ES6 Promise doesn’t so far.
An Observable is like a Stream (in many languages) and allows to pass zero or more events where the callback is called for each event. Often Observable is preferred over Promise because it provides the features of Promise and more. With Observable, it doesn’t matter if you want to handle 0, 1, or multiple events. You can utilize the same API in each case. Observable also has the advantage over Promise to be cancelable. If the result of an HTTP request to a server or some other expensive async operation isn’t needed anymore, the Subscription of an Observable allows canceling the subscription, while a Promise will eventually call the success or failed callback even when you don’t need the notification or the result it provides anymore. Observable provides operators like map, forEach, reduce, … similar to an array. There are also powerful operators like retry(), or replay(), … that are often quite handy.

13. What Are The New Features Of Angular2?
Answer: Angular 2 is written entirely in Typescript and meets the ECMAScript 6 specification :

Component-Based- Angular 2 is entirely component-based. Controllers and $scope are no longer used. They have been replaced by components and directives.
Directives- The specification for directives is considerably simplified, although they are still subject to change. With the @Directive annotation, a directive can be declared.
Dependency Injection- Because of the improved dependency injection model in Angular2, there are more opportunities for component / object-based work.
Use of TypeScript-TypeScript is a typed superset of JavaScript which has been built and maintained by Microsoft and chosen by the AngularJS team for development. The presence of types makes the code written in TypeScript less prone to run-time errors. In recent times, the support for ES6 has been greatly improved and a few features from ES7 have been added as well.
Generics- TypeScript has generics which can be used in the frontend.
Lambdas with TypeScript- In TypeScript, lambdas are available.
Forms and Validations- Forms and validations are an important aspect of frontend development. Within Angular 2 the Form Builder and Control Group are defined.

14. What Is The Need For Typescript In Angular2?
Answer: Understanding the need for TypeScript file in Angular2 applications: JavaScript rules in Web development. Its the most popular language for developing web application UI. For may, application developers having exposure in languages like Java and C#, creating the front end of a Web application in JavaScript is a very cumbersome process. For example, if the user wants to create a class Employee in JavaScript. There is no class keyword in JavaScript so the code will be as follows-
This Customer.ts will compile to the above JavaScript code.

So TypeScript provides the following advantages over JavaScript-

Structure the code- There were many different coding styles for JavaScript. This leads to unstructured code. With TypeScript, we create a structured code.
Use object-oriented programming paradigms and techniques- There is a lack of object-oriented design paradigms and techniques in JavaScript. This is not the case in TypeScript. It makes use of Objected Oriented features like Polymorphism, Inheritance, etc.
Standard Coding guidelines- There is no Type checking in JavaScript. The code style needs to be defined. Hard to enforce a style guide. TypeScript overcomes this issue with features like Code Analysis and Navigation, Documentation, Intellisense, etc.

15. What Is The Use Of Codelyzer In Angular 2 Application?
Answer: All enterprise applications follow a set of coding conventions and guidelines to maintain code in a better way. Codelyzer is an open source tool to run and check whether the pre-defined coding guidelines have been followed or not. Codelyzer does only static code analysis for angular and typescript project.

Codelyzer runs on top of tslint and its coding conventions are usually defined in tslint.json file. Codelyzer can be run via angular CLI or npm directly. Editors like Visual Studio Code and Atom also supports catalyzer just by doing basic settings.

16. How to declare a component in Angular 2?
Answer: Components in Angular 2 are simply directives that are always associated with a direct template. Angular 2 components have an extremely well-defined life-cycle. When working with angular components, we can make use of interfaces which allows us to implement functionality for different times in a component’s lifecycle. A component must belong to a NgModule in order for it to be usable by another component or application. Components can even control their runtime behavior by implementing various Life-cycle hooks.

17. What do you mean by a structural directive in Angular 2?
Answer: Structural directives are used to manipulate DOM in angular. Structural directives are responsible for HTML layout. By adding, removing, or manipulating 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 it is 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.

18. What Is ECMAScript?
Answer: ECMAScript is a subset of JavaScript. JavaScript is basically ECMAScript at its core but builds upon it. Languages such as ActionScript, JavaScript, JScript all use ECMAScript as its core. As a comparison, AS/JS/JScript are 3 different cars, but they all use the same engine… each of their exteriors is different though, and there have been several modifications done to each to make it unique. Angular2 supports ES6 and higher versions.

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

20. How to implement a Datagrid Table with Angular 2 and PrimeNG?
Answer: Angular2 PrimeNG Tutorial- Create a Hello World application using DataTable Grid.

21. How can you handle errors in Angular 2 Applications?
Answer: The Angular 2 Applications provide with the option of error handling. The errors in Angular 2 can be handled by including the ReactJS catch library and later using the catch function.

The catch function, which is used after adding the catch library contains the link to the Error handler function.
And in this error, handler function, the errors are sent to the error console, and also the errors are thrown back to continue the execution.
So, whenever an error occurs it will be redirected to the error console of the web.

22. What are the new features of Angular 2?
Answer: Angular 2 is a platform that encompasses a wide range of capabilities. Some new features were added in Angular 2 which includes:
Universal server rendering: It is the library which is used to make building universal apps a smooth experience.

23. In Angular 2 Module consists of what arrays?
Answer: Angular 2 Module consists of Bootstrap Array, Export Array, Import Array.

24. How do you resolve a template URL relative to a Component class?
Answer: By specifying the modules to be module.id in the Component decorator. (Note: while this is still needed when using SystemJS, it is not necessary anymore when using Webpack module bundler for Angular 2 projects.)

25. What are Event emitters?
Answer: An Event emitter is a class defined in a core module that can be used by components and directives to emit custom events.

26. What is TestBed?
Answer: Class to create testable component fixtures.

27. What are the possible ways to bind component properties to an associated template?
Answer:  Interpolation binding, one-way binding, two-way binding.

28. Explain The Architecture of Angular 2?
Answer:  Angular 2.0 is a Framework, not just a library as like of Angular 1. It has eight main elements in its architecture. Go through this link: Angular 2 Architecture.

29. What is Import array in Angular 2?
Answer: The import array can be used to import the functionality from other Angular JS modules.

30. What’s the used of @Outputs in Angular 2?
Answer: The @Outputs is used to bind a property of components to send data from one component to another component. This is used to handle one-way communication from the child to the parent component.

31. What’s the difference between form, FormGroup, and FormControl? How do they work together?
Answer: FormGroup tracks the value and validity state of a group of AbstractControl instances. FormControl does the same for individual control. form is a directive that Angular automatically attaches to each

tag. It has its own ‘valid’ property which is true only if every contained control is valid.

32. Explain host decorator in Angular 2?
Answer: The host decorators in Angular 2 bind the properties of components with UI element values. The properties inside a component class definition which are decorated with @HostBinding are accessed in a template from the assigned property that is @HostBinding()title=’Our title'( whatever the title is).

33. What Are The Advantages And Disadvantages Of Art Compilation?
Answer:

Advantages :

Faster download: Since the app is already compiled, many of the angular compiler related libraries are not required to be bundled, the app bundle size gets reduced. So, the app can be downloaded faster.
Lesser No. of Http Requests: If the app is not bundled to support lazy loading (or whatever reasons), for each associated HTML and CSS, there is a separate request goes to the server. The pre-compiled application in-lines all templates and styles with components, so the number of Http requests to the server would be lesser.
Faster Rendering: If the app 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 component to be downloaded, and then the time is taken by the compiler to compile the app. With AOT compilation, this is optimized.
Detect error at build time: Since the compilation happens beforehand, much compile-time errors can be detected, providing a better degree of stability of the application.

Disadvantages

Works only with HTML and CSS, other file types need a previous build step.
No watch mode yet must be done manually (bin/ngc-watch.js) and compiles all the files.
Need to maintain AOT version of the bootstrap file (might not be required while using tools like CLI).
Needs cleanup step before compiling.

34. What Is Art Compilation?
Answer: AOT compilation stands for Ahead Of Time compilation, in which the angular compiler compiles the angular components and templates to native JavaScript and HTML during the build time. The compiled Html and JavaScript is deployed to the webserver so that the compilation and render time can be saved by the browser.

35. What Is Shadow Dom? How Is It Helping Angular 2 To Perform Better?
Answer: Shadow DOM is a part of the HTML spec which allows developers to encapsulate their HTML markup, CSS styles, and JavaScript. Shadow DOM, along with a few other technologies, gives developers the ability to build their own 1st class tags, web components, and APIs just like the

36. How would you define custom Typings to avoid editor warnings?
Answer: Well, in most of the cases, the 3rd party library comes with its own .d.ts file for its type definition. In some cases, we need to extend the existing type by providing some more properties to it or if we need to define additional types to avoid Typescript warning.

If we need to extend the type definition for an external library, as a good practice, we should not touch the node_modules or existing typings folder. We can create a new folder, say “custom-typings” and keep all customized type definition in that.

To define typings for application (JavaScript/Typescript) objects, we should define interfaces and entity classes in models folder in the respective module of the application.

37. What is lazy loading and How to enable lazy loading in angular 2?
Answer: Most of the enterprise application contains various modules for specific business cases. Bundling whole application code and loading will be huge performance impact at initial call. Lazy lading enables us to load only the module user is interacting 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 (NgModule) based on the application business case. 

38. What Is Primeng? How Can It Be Used With Angular2?
Answer: PrimeNG is a collection of rich UI components for Angular 2. PrimeNG is a sibling of the popular JavaServer Faces Component Suite, PrimeFaces. All widgets are open source and free to use under Apache License 2.0, a commercial-friendly license. PrimeNG is developed by PrimeTek Informatics, a company with years of expertise in developing open source UI components. AngularJS makes it possible to use predefined components for development like tables etc. This helps developers save time and efforts. Using PrimeNG developers can create awesome applications in no time.

39. Which other PrimeNG components have you used with Angular 2?
Answer: Create a simple PrimeNG application using PrimeNG Components like PrimeNG Button, Confirmation Box, Text Box.

40. What are pipes in Angular 2? Explain?
Answer: Pipes in Angular 2 are a way to transform and format data right from your templates Out of the box you get pipes for dates, currency, percentage and character cases, but you can also easily define custom pipes of your own. Here, for example, we create a pipe that takes a string and reverses the order.

41. List out the differences between ActivatedRoute and RouterState, with reference to Angular 2?
Answer: Here are some of the differences between ActivatedRoute and RouterState with reference to Angular 2:-
ActivatedRoute consists of the information about a route associated with a component loaded in an outlet. Whereas, RouterState represents the state in which the writer actually is.
We need ActivatedRouteSnapchat to traverse all the activated routes. Whereas, during navigation, after redirects have been applied, the router creates a RouterStateSnapshot.
ActivatedRouteSnapshot has old data. When route changes, ActivateRouteSnapshot has data from the previous route. Whereas, the RouterState cares about application components, or, to be more specific, about their arrangements.

42. What Is Component In Angularjs 2?
Answer: In Angular, a Component is a special kind of directive that uses a simpler configuration which is suitable for a component-based application structure.

43. What Is An Angular 2 Component?
Answer: Each component is comprised of a template, which is the HTML for the user interface. Add to that a class for the code associated with a view. The class contains the properties and methods, which perform actions for the view,A component also has metadata, which provides additional information about the component to Angular.

44. Explain the concept of lazy loading in Angular 2?
Answer: Lazy loading is a module which is used to decrease the start-up time. When lazy is used, then our system application does not need to load everything at once. It only needs to load what the user expects to see when the application first loads. The modules which are lazily loaded will only be loaded when the user navigates to their routes. Lazy loading improves the performance of our system applications. It keeps the initial payload small and these smaller payloads lead to faster download speeds. It helps in lowering the resource cost, especially on mobile networks. If a user doesn’t visit a section of the application, they won’t ever download those resources. The concept of lazy loading in angular requires us to format the application in a certain way. All the assets that are to be lazy-loaded should be added to its own module.

Note: Browse latest AngularJs Interview Questions and Angular Tutorial Videos. Here you can check Angular Training details and Angularjs Training Videos for self learning. Contact +91 988 502 2027 for more information.

All AngularJS Interview Questions