Best 45 Angularjs Interview Questions And Answers

Best 45 Angularjs Interview Questions And Answers

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

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

3. When will ngOnInit be called?
Answer: Called once, after the first ng On Changes.

4. Why is it (potentially) bad if SharedModule provides a service to a lazy-loaded module?
Answer:
You will have two instances of the service in your application, which is often not what you want.

5. What is the AOT compilation?
Answer: AOT stands for Ahead of Time. It is the compilation in which Angular compiles the components and templates to JavaScript and HTML while developing.

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

7. How are the services injected to your application?
Answer:
Via Angular’s DI (Dependency Injection) mechanism.

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

9. What is an async pipe?
Answer:
A: An impure pipe that accepts a promise or observable as input and eventually returns emitted values.

10. What types of pipes are supported in Angular 2?
Answer:
Pure and impure pipes (async pipes a kind of impure pipe).

11. What is an impure pipe?
Answer: A pipe that is executed during every component change detection cycle (i.e., often – every keystroke, mouse move).

12. What is the use of ngForTrackBy directive?
Answer: For iterating over a collection in Angular 2, the ngFor directive is used which instantiates a template once per item from the collection. If a date needs to be changed at some point in the collection, then a problem occurs because angular cannot keep a track of items in the collection and has no knowledge of the items which were added or deleted. This results in the deletion of all the DOM elements that are associated with the data and are again created. If the collection is big, then it becomes more complicated because a lot of DOM manipulation occurs which are expensive. So, to solve this problem, a track function is used which takes the index and the current item as arguments and returns the unique identifier for this item.

13. What selector forces a style down through the child component tree into all the child component views?
Answer: Use the /deep/ selector along with :host pseudo-class selector.

14. What does :host-context() pseudo-class selector target?
Answer: The: host-context() selector looks for a CSS class in any ancestor of the component host element, up to the document root.

15. When do you use template-driven vs model-driven forms? Why?
Answer: Template-driven forms make more sense for simpler forms, at least in terms of validation. Model-driven or Reactive forms lend themselves to easier testing of the validation logic, so if that’s complex, Reactive forms make more sense. There’s also the issue of asynchronous (template-driven forms) vs. synchronous (model-driven). (Interview Questions and Answers)

16. What is patchValue used for?
Answer:
Setting a form value (one or more fields with an object) bypassing validation.

17. Just-in-time (JIT) compiles the app in the browser, at runtime, as the application loads – this is the standard development approach. JIT is useful for development, but its performance concerns me – how would JIT scale for enterprise-level applications?
Answer: This setup reminds me of Google Web Toolkit (GWT – GWT had the same promise – Code in Java and compile to JavaScript and you will get the best of both worlds. A strongly typed language with tooling support and performance of standard JavaScript at runtime. But as any serious GWT developer knows, the GWT compiler became the bottleneck. Compilation and executing test cases ended up taking so much time that everyone was looking for any hack or trick to make life more bearable. I hope Angular 2 won’t share the same fate. 

Note: In Practice, I have observed that JIT skips errors while hot loading and reports it when you restart the server. Better to be a little careful and restart (npm start) the development server at least twice a day. (AngularJs Training Online)

18. Bootstrap (main.ts) Appears Unnecessary
The file “main.ts” appears unnecessary. Why do we have to write and manage a class which is not my own business concern (application logic)? The code in this file is all about bootstrapping the application, and the worst part is that you would actually need a pair of files – one for development and another one for production. Is it possible to replace the separate files with an annotation that could be marked in the root module (E.g. Line 7 below)?
Answer:
1. import { NgModule } from ‘@angular/core’;
2. import { BrowserModule } from ‘@angular/platform-browser’;
3. import { FormsModule } from ‘@angular/forms’;
4.
5. import { AppComponent } from ‘./app.component’;
6.
7. @NgPlatformBrowser(true/false) // where true means production mode and false means development mode.
8. @NgModule({
9. imports: [
10. BrowserModule,
11. FormsModule
12. ],
13. declarations: [
14. AppComponent
15. ],
16. bootstrap: [ AppComponent ]

19. What is different between Angular 2 and Angular?
Answer: Angular 2 is totally different than Angular. It is based on component and modules instead of controllers and scope to develop web applications.

20. How do you define a 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, 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.
Syntax: –
function transition (state Change Exp r: string, steps: Animation Metadata | Animation Metadata []):Animation Transition Metadata;

21. What are the advantages of using Angular 2?
Answer:
There are following advantages of using Angular 2 instead of Angular.

Its more structured framework than Angular to manage applications.
Angular 2 is totally based on the component and module to develop web applications.
Angular 2 is a fully mobile-oriented framework to develop mobile applications.
It supports multiple languages to develop application such as Typescript, ES5, ES6, etc.

22. Dependency Injection (DI)?
Answer: Dependency Injection (DI) is a really great and powerful feature of the framework. It reminds me of a something I heard t in the Spiderman movie: “With great power comes great responsibility”. I have a strong feeling that most production issues for Angular 2 applications will have root cause related to Dependency Injection. Developers who don’t have good past experience with DI patterns and frameworks should look at it very carefully, especially the Prototype and Singleton behavior of services.

Apart from the above six concerns, the framework lacks constraints to force developers to do the right thing. I see the potential to do things the wrong way being too easy; like a service being marked as a component or vise versa, the same is true about directives, and even components are essentially directives and so on. That said, I guess the potential for mistakes is a concern with any technology or framework.

23. What are the components in Angular2?
Answer: The components are used in Angular 2 framework to develop web applications into modules. Angular 2 has the following components:

  • Modules
  • Component
  • Templates
  • Metadata
  • Service

24. How would you select all the child components’ elements?
Answer:
With the @ViewChildren decorator, like for example:

@ViewChildren(ChildDirective) viewChildren: QueryList; company

25. What is the difference between a module’s forRoot() and Fairchild() methods and why do you need it?
Answer:
forRoot and child are conventional names for methods that deliver different import values to root and feature modules.

26. What’s the difference between dirty, touched, and pristine on a form element?
Answer: Dirty means it contains user data, touched means the user has at least done something with a particular control (perhaps just literally ‘touched’ it by giving it focus?), and pristine means the control has not been touched at all by the user.

27. What’s the advantage of using Form Builder?
Answer:
Reduces repetition and clutter by handling details of control creation for you.

28. When will ngOnInit be called?
Answer: Called once, after the first ngOnChanges.

29. What would you consider a thing you should be careful doing on onNgInit()?
Answer: You cannot expect the component’s children’s data-bound properties to have been checked at this point.

30. How would you make use of onNgInit()?
Answer:
PA: Fetch initial component data (e.g. from server).

31. How would you control the size of an element on resize of the window in a component?
Answer:
@HostListener(‘window:resize’, [‘$event’]) one size(event: any) { this.calculateBodyHeight(); }

32. What would be a good use for NgZone service?
Answer: Running an asynchronous process outside of Angular change detection.

33. What is the difference between RouterModule.forRoot() vs RouterModule.forChild()? Why is it important?
Answer:
forRoot is a convention for configuring app-wide Router service with routes, whereas for a child is for configuring the routes of lazy-loaded modules.

34. How would you use a Route Guard?
Answer: You would implement CanActivate or CanDeactivate and specify that guard class in the route path you’re guarding.

35. How would you select a custom component to style it?
Answer:
Using the: host pseudo-class selector in your component’s styles.

36. What is the difference between onNgInit() and constructor() of a component?
Answer: A directive’s data-bound input properties are not set until after construction, so that’s one difference.

37. What is a pure pipe?
Answer:
A pipe that is only executed when Angular detects a pure change to the input value (e.g. new primitive object or new object reference).

38. What are some differences between Angular 2 and 4?
Answer:
Improvements in AOT; allowing else clause in ngIf, few other things.

39. How do you reference the host of a component?
Answer:
Let DI inject an ElementRef into the constructor of your component.

40. What is the purpose of exports in an Ng Module?
Answer: Provide components, directives, pipes to other modules for their usage.

41. ”Code in HTML” or “HTML in Code” Dilemma?
Answer: If we look at a component, we are basically embedding HTML in Typescript code from a developer’s perspective. Is this the right thing to do? I remember how the Java community started with Servlets where we embedded HTML in code, but then quickly realized the mistake and reversed it. Technologies like JSP, ASP, and PHP are based on the same conceptual model where we embed code inside HTML.

Both approaches have their own advantages and disadvantages. Moreover, we can’t get away with it as long as we want to dynamically generate the UI. Angular 2 has adopted HTML in the code – Is it the right approach for Angular? I don’t know – probably time will tell. But the good part is that Angular 2 supports having HTML partials in separate files which is great for separating code from markup but comes with its own set of problems, especially for UX guys.

42. Explain component-specific hooks?
Answer: ngafterContentinit: It initializes the component content
ngAfterConctentChecked: It checks the binding of the external content.
ngafterViewinit: It creates the component view.
ngAfterviewChecked: It checks the bindings of the component’s view.

43. What is Angular 2 and TypeScript?
Answer: Angular 2 is built with features of ES6 (and ES7), Web Components in mind, and targeting evergreen browsers.
TypeScript is a typed superset of JavaScript which has been built and maintained by Microsoft and chosen by the AngularJS team for development.

44. Is ES6 Typescript?
Answer: ES6 (also called ES2015) is the next iteration of JavaScript, but it does not run in today’s browsers.
There are quite a few transpilers that will export ES5 for running in browsers.
TypeScript provides an optional typing system while pulling in features from future versions of JavaScript (ES6 and ES7).

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