You are on page 1of 21

1.

 What is Angular?

Angular is a platform that makes it easy to build applications with the web. Angular combines declarative templates,
dependency injection, end to end tooling, and integrated best practices to solve development challenges. Angular
empowers developers to build applications that live on the web, mobile, or the desktop

2. What are the key Differences between Angular vs JQuery?

Below is the list of points that describe the differences between Angular vs JQuery

 Jquery is a library used for DOM manipulation whereas Angular is a framework.


 Jquery has got nothing to do with the models; Angular is used to create SPA (single page applications).
 Jquery does not have two-way binding features whereas Angular has key features like routing, directives, two-way
data binding, models, dependency injection, unit tests etc.
 Jquery becomes complex and difficult to maintain when the size of project increases but in case of Angular things
are different as they are manageable at big project size.
 Many a time happens that one has to write more codes in jquery to achieve same functionality whereas Angular
reduces these criteria as the codes are generally are not lengthy as compared to jquery.

3. What are the advantages and disadvantages of Angular?

Angular has many advantages and disadvantages and it depends on every person’s need and requirements. From my
personal experience, these are some of the pros and cons I’ve noticed.

Advantages:

• Angular is developed using Typescript enabling us to optimize the code using OOPS concept.

• Being a Google product, you have a lively and active support community along with the host of advantages provided by
Google.

• CLI - The Angular CLI makes it easy to setup angular environment leading to effortless skeleton creation.

• There are numerous active forums where you can get immediate and reliable support.

Disadvantages:

• The web developer has to be familiar with TypeScript before starting development on Angular.

• When you are going to create a simple web app of approximately 2MB, it is ridiculous to use Angular with massive 200MB
‘node_modules’

4. What are the advantages of Angular over Angularjs?

Better performance because of these reasons:

 Better change detection.


 Ahead of Time compilation (AOT) improves rendering speed.
 Lazy Loading.
 TypeScript can be used for developing Angular 2 applications.
 Better syntax and application structure.

5. What are the lifecycle hooks for components?

Angular application goes through an entire set of processes or has a lifecycle right from its initiation to the end of the
application.

 ngOnChanges()
 Used in pretty much any component that has an input.
 Called whenever an input value changes
 Is called the first time before ngOnInit
 ngOnInit()
 Used to initialize data in a component.
 Called after input values are set when a component is initialized.
 Added to every component by default by the Angular CLI.
 Called only once
 ngDoCheck()
 Called during all change detection runs
 A run through the view by Angular to update/detect changes
 ngAfterContentInit()
 Called only once after first ngDoCheck()
 Called after the first run through of initializing content
 ngAfterContentChecked()
 Called after every ngDoCheck()
 Waits till after ngAfterContentInit() on first run through
 ngAfterViewInit()
 Called after Angular initializes component and child component content.
 Called only once after view is initialized
 ngAfterViewChecked()
 Called after all the content is initialized and checked. (Component and child components).
 First call is after ngAfterViewInit()
 Called after every ngAfterContentChecked() call is completed
 ngOnDestroy()
 Used to clean up any necessary code when a component is removed from the DOM.
 Fairly often used to unsubscribe from things like services.
 Called only once just before component is removed from the DOM.

In my experience as an Angular developer, I primarily use only four of these hooks. Mostly because I don’t want to do
something to a component after the content has already been checked.

 ngOnChanges()
 ngOnInit()
 ngAfterViewInit()
 ngOnDestory()

6. What Is SPA (Single Page Application)?

Single-Page Applications (SPAs) are web applications that fit on a single HTML page. It dynamically updates the web page as
the user performs actions on the app.

SPAs use AJAX and HTML to create quick and responsive web apps. A single page load extracts all the web app code (JS,
HTML, CSS).
Thus the user navigates to different parts of the application quickly as it happens without refreshing the whole page.

The main characteristics of Single-Page Applications are as follows.

 Its UI is fast and responsive. Also, the Back/Forward buttons present in the UI work properly.
 IT contains more JavaScript code than actual HTML as compared to other applications.
 Dynamic data loading occurs from the server-side. The API uses restful web service with JSON format.
 It allows to pre-load and cache all the app pages. Thus fewer data download requests are made towards the server.
 Applications written in Angular are cross-browser compliant. It automatically handles the JavaScript code suitable
for each browser.
 Even if the user has lost the internet connection, then also the SPA can work. As all the pages load in the starting
itself.

7. What is npm and why do we need it?

npm is a package manager for the JavaScript programming language. It is the default package manager for the JavaScript
runtime environment Node.js. It consists of a command line client, also called npm, and an online database of public and
paid-for private packages, called the npm registry.

A package.json file in our application defines the dependencies that we want to download for our application.

Example:

npm install <module> --global // Where <module> is the name of the module you want to install globally
npm install <module> -g // Where <module> is the name of the module you want to install globally, using the -g alias

Read more https://gist.github.com/ankurk91/48e0844320601ebc0cae

8. What are components In Angular?

Components are the most basic building block of a UI in Angular applications and it controls views (HTML/CSS). They also
communicate with other components and services to bring functionality to your applications.

Technically components are basically TypeScript classes that interact with the HTML files of the components, which get
displayed on the browsers.

The component is the core functionality of Angular applications but you need to know to pass the data into the components
to configure them.

What’s an NgModule made out of?

An NgModule is collection of metadata describing components, directives, services, pipes, etc. When you add these
resources to the NgModule metadata, Angular creates a component factory, which is just an Angular class that churns out
components.

declarations - Declare views to make them privately available in this module.

exports - Makes the declared view public so they can be used by other modules.
imports - This is where you import other modules.

providers - Defines services that can be injected into this module’s views.

bootstrap - The component used to launch the app, the AppComponent by default. All apps must have at least one

@NgModule({    
  declarations: [
    AppComponent
      ],
  imports: [
    CommonModule
 
  ],
  exports:[],
  bootstrap: [AppComponent],
  providers: [DataService]
})
10. What are differences between Constructors and OnInit?

Constructors

 The constructor is a default method runs when a component is being constructed.


 The constructor is a typescript feature and it is used only for a class instantiations.
 The constructor called first time before the ngOnInit().

ngOnInit

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

11. Waht are types of bindings in angular ?

1. Interpolation - <h1>{{user.name}}</h1> //interpolation is in braces


2. Two way binding - <input [(ngModel)]=”user.name”/>
3. One way binding - <h1 [innerText]=”user.name”></h1> //Bindings like inner text
4. Event Binding - <button (click)=”userData()”>Send</h1> //Binding events like click

12. Below compilation option create smaller in size and faster in performance angular distributed
package

JIT

AOT
13. What is Redux?

Redux is an application state manager for JavaScript applications, and keeps with the core principles of the Flux-architecture
by having a unidirectional data flow in your application.

Where Flux applications traditionally have multiple stores, Redux applications have only one global, read-only application
state. This state is calculated by "reducing" over a collection or stream of actions that update it in controlled ways.
14. What is Angular material design, and should we use it or not?

Angular Material is a UI component framework and while you’re not required to use it. UI Component frameworks help us to
organize the layout and the responsive on the website but we have a lot of them in the market like bootstrap and other and
we can choose the look and feel we prefer.

15. What is Angular routing and navigation?

The Angular Router enables navigation from one view to the next as users perform application tasks. It can interpret a
browser URL as an instruction to navigate to a client-generated view. The developer is allowed to set up URL names,
parameters and contaminated with CanAuthenticate we can validate user authentication

16. How to apply CSS Class Conditionally?

Angular provide some way to add class with the condition

There are different type :

Type one

[class.my-class]="step=='step1'"

Type two

[ngClass]="{'my-class': step=='step1'}"

Type three

[ngClass]="{1:'my-class1',2:'my-class2',3:'my-class4'}[step]"

Type four

[ngClass]="(step=='step1')?'my-class1':'my-class2'"
17. Explain angular directives decorators with an example.

Angular directives allow you to attach behavior to elements in the DOM and reuse it across your project.

The framework already comes with a number of convenient directives like NgStyle, NgIf, NgFor, and NgSwitch.

There are three kinds of directives in Angular:

Components - The component is a directive with their own templates and it is responsible for how a component should be
processed, instantiated and used at run-time.

Structural Directives - The structural directive is a directive and it is responsible for change the DOM layout by adding,
removing, and manipulating elements.

The most of the common built-in structural directives are NgIf, NgFor, and NgSwitch.

Attribute Directives - The Attribute directive is a directive and it is responsible for change the behavior of a specified
element or component.
An attribute directive example

Create the directive class file in a terminal window with the CLI command

ng generate directive highlight

Command will create a highlight directive with default code template.

import { Directive, ElementRef } from '@angular/core';

@Directive({
selector: '[appHighlight]'
})
export class HighlightDirective {
constructor(el: ElementRef) {
el.nativeElement.style.backgroundColor = 'yellow';
}
}

Usage

<p appHighlight>Highlight me!</p>

Above code change paragraph background color to yellow.

18. What is the difference between directive and component?

Components are the most basic UI building block of an Angular app. A component must belong to an NgModule in order
for it to be available to another component or application. To make it a member of an NgModule, list it in
the declarations field of the @NgModule metadata.

Example

import { Component } from "@angular/core";  

//decorator  
@Component({  
     
    selector: 'my-App',  
    template: '<h1>{{name}}</h1>'  
})  
  
export class AppComponent {  
    name: string = "Angular 2"  
}  

Directives are just "behaviour" added to existing elements and components.

Example of ngClass

<p [ngClass]="{'blue'=true, 'yellow'=false}">


Angular Directives Are Cool!
</p>

<style>
.blue{color: blue}
.yellow{color: yellow}
</style>

19. What is the difference between client-side and server-side rendering? Server Side Rendering

You extracted the HTML file/String from your Angular code on the server and then sent a plain and simple html file/string to
the client/browser that it’ll immediately show to the user without any extra step.
Client Side Rendering

You didn’t extracted the html string from javascript code on the server and sent the javascript file to the client/browser. Now,
Browser can not show anything to the user immediately, Because now it’s the browser’s job to execute the javascript code,
get the html string and then show it to the browser. This step can take fairly long time if your javascript file is big and you
have a lot of components.

20. What is lazy loading? Lazy loading modules speeds up our applications startup time.

Lazy loading creates multiple bundles and loads them on demand in runtime.

If we had loaded all our components and templates into one big bundle, it would lead to a large performance penalty.

const routes: Routes = [


{ path: 'lazy', loadChildren: './lazy.module#LazyModule'}
];

You need to use the loadChildren() method to lazy load the feature module:

21. What is AOT compilation?

AOT compilation stands for Ahead Of Time compilation, in it angular compiles components to native JavaScript and HTML
during the build time instead of runtime.

This drastically improves the performance of the Angular  application.With Just in time compilation ,the compilation happens
on the users browser at runtime.

In the case of Ahead of time compilation ,the application is compiled and optimized at the build time instead of run time.So
this improves the rendering of the application UI.This approach should be used in production builds.

22. What are advantages of Angular HttpClient over previous Http?


HIDE
favorite_border

The HttpClient interface is pretty much unchanged from the old Http interface. The big difference is that
HttpClientModule has better support for middleware (i.e .HTTP interceptors).

Some of the feature benefits:

 Strongly typed response body access


 JSON assumed by default (no more need to do .map(t=>t.json())
 Better support for interceptors as middleware
 Immutable request/response objects
 Progress events for request upload/response download

 23. How to perform DOM manipulation in Angular components?


 HIDE
 favorite_border
 Essentially ViewChild and ContentChild are used for component communication in Angular. Therefore, if a
parent component wants access of child component then it uses ViewChild or ContentChild.
 @Component({
 ....
 templateUrl: 'mytemplate.html'
 })

 export class MyComponent{
 @ViewChild('selector') private someName;
 constructor() {
 //this is your dom
 //this.someName.nativeElement
 }
 }
 and in your template class you got to specify who is that selector
 <div #selector> </div>

24. What is the difference between AngularJS and Angular?


HIDE
favorite_border

AngularJS

The architecture of AngularJS is based on model-view-controller (MVC) design. The model is the central component
that expresses the application's behavior and manages its data, logic, and rules. The view generates an output based
on the information in the model. The controller accepts input, converts it into commands and sends the commands to
the model and the view.

Angular 

In Angular, controllers and $scope were replaced by components and directives. Components are directives with a
template. They deal with a view of the application and logic on the page. There are two kinds of directives in Angular .
These are structural directives that alter the layout of the DOM by removing and replacing its elements, and
attributive directives that change the behavior or appearance of a DOM element.

Features of New Angular:

1. Backward Compatibility: So, application written using Angular will be compatible with Angular 7 as well.
2. TypeScript: The version of TypeScript is upgraded from 1.8 to 2.1. This will improve the speed of ngc
(angular compiler) and you will get better type checking throughout your application.
3. In-Built Compiler: Angular comes with the inbuilt compiler to report the template errors right in the IDE.
Google emphasizes improvements in tooling as well as reduced code generation.
4. Reduction of Code: They have made changes to AOT generated code such that you will find reduction in
the size of the generated code for the components by around 60% in most of the cases..
5. Animation Package: They have segregated animation package from @angular/core as a separate and
dedication package. Therefore, if you don’t use animations, this extra code will not end up in your
production bundles.
6. Improved *ngIf and *ngFor: if/else style syntax has been introduced where you can assign local variables
such as when unrolling an observable.
7. Flat ES Modules: Modules are shipped as flattened version that helps in tree-shaking and reduce the size of
generated bundles. It also speeds up the building process, transpilation and loading in the browser in certain
scenarios.
8. Dependency injection - Angular implements unidirectional tree-based change detection and uses
Hierarchical Dependency Injection system. This significantly boosts performance for the framework.  
9. Mobile Support - AngularJS was not built with mobile support in mind, but Angular 2 and 4 both feature
mobile support.
10. 25. What's the difference between an Angular component and module?
11. HIDE
12. favorite_border
13. Angular Component
14. A component is one of the basic building blocks of an Angular app. An app can have more than one
component. In a normal app, a component contains an HTML view page class file, a class file that controls
the behavior of the HTML page and the CSS/scss file to style your HTML view. A component can be created
using @Component decorator that is part of @angular/core module.
15. import { Component } from '@angular/core';
16. and to create a component
17. @Component({selector: 'greet', template: 'Hello {{name}}!'})
18. class Greet {
19. name: string = 'World';
20. }
21. Angular Module
22. An angular module is set of angular basic building blocks like component, directives, services etc. An app can
have more than one module.
23. A module can be created using @NgModule  decorator.
24. @NgModule({
25. imports: [ BrowserModule ],
26. declarations: [ AppComponent ],
27. bootstrap: [ AppComponent ]
28. })
29. export class AppModule { }

26. What are the differences between reactive forms and template driven forms?
HIDE
favorite_border

Reactive form 

Can be used in the following situation

 Complex forms with more number of fields.


 Multiple complex validation are there. Custom validations are required
 Require JSON structure to be send with the values in the form.

We can get entire form in a structured way by using "form.value"

<form [formGroup]="form">
First Name <input formControlName="firstName">
Last Name <input formControlName="lastName">
</form>

We can get the values from the form like below

{
"firstName": "FName",
"lastName": "LName",
}

by calling form.value, where form is FormGroup Variable that we created.

Template Driven Form :

It can be used when using simple forms. Like login page. With the two way data binding. We can simply assign value
to variable from UI and vice versa.

Simple example is if we are giving two way binding for the below input.
<input [(ngModel)]="username">

27. How do you create two-way data binding?


HIDE
favorite_border

Angular provides us with a directive ngModel to achieve two-way data binding. It is very simple and straightforward
to use ngModel directive, as shown in the listing below:

import {Component} from '@angular/core';


@Component({
moduleId:module.id,
selector:'my-app',
template:`
<div class="container">
<input [(ngModel)]='name' />
<br/>
<h1>Hello {{name}}</h1>
</div>
`
})
export class AppComponent{
}

28. What is impure pipe in Angular?


HIDE
favorite_border

In angular, a pipe can be used as pure and impure

What is pure or impure pipe?

In simple words,

impure-pipe works for every change in the array and 

pure-pipe works only the component is loaded.

How to make pipe pure or impure?


@Pipe({
name: 'sort',
pure: true | false // true makes it pure and false makes it impure
})
export class myPipe implements PipeTransform {

transform(value: any, args?: any): any {


return null;
}
}

9. Why different life cycle hooks are needed for a component?


HIDE
favorite_border

A component in Angular has a life-cycle, a number of different phases it goes through from birth to death.

Lifecycle hooks allow custom logic to be added at various component stages and are implemented as class methods

30. Why would you use angular cli?


HIDE
favorite_border

The Angular CLI is used for much more than just creating an Angular project. It can be used to create components,
services, pipes, directives and more. Also it helps in building, serving, testing etc. CLI itself is quite something to learn
about, it makes Angular development workflow much easier and faster.

Below are some command of Angular CLI to create different controls:

 Component: ng g component my-new-component


 Directive: ng g directive my-new-directive
 Pipe: ng g pipe my-new-pipe
 Service: ng g service my-new-service
 Class: ng g class my-new-class
 Interface: ng g interface my-new-interface
 Enum: ng g enum my-new-enum
 Module: ng g module my-module

31. Why do you Typescript with Angular?


HIDE
favorite_border

Typescript is a superset of Javascript. Earlier, Javascript was the only client side language supported by all browsers.
But, the problem with Javascript is, it is not a pure Object Oriented Programming Language. The code written in JS
without following patterns like Prototype Pattern, becomes messy and finally leading to difficulties in maintainability
and reusability. Instead of learning concepts (like patterns) to maintain code, programmers prefer to maintain the
code in a OOP approach.

Benefits of using Typescript:

 Pure OOPS as Typescript offers concepts like Generics, Interfaces and Types (a Static Typed Language) which
makes it is easier to catch incorrect data types passing to variables.
 TS provides flexibility to programmers experienced in java, .net as it offers encapsulation through classes and
interfaces.
 JS version ES5 offers features like Constructor Function, Dynamic Types, Prototypes. The next version of
Javascript ie ES6 introduced new feature like Class keyword but not supported by many browsers.
 TS offers Arrow Functions (=>) which is an ES6 feature not supported by many browsers directly but when
used in TS, gets compiled into JS ES5 and runs in any browser.
 TS is not the only alternative to JS, we have CoffeScript, Dart(Google).
 Finally, it is like, TS makes life easier when compared to JS.

 32. What's the difference between dirty, touched, and pristine on a form element?
 HIDE
 favorite_border
 The form control instance on our model encapsulates state about the control itself, such as if it is currently
valid or if it’s been touched.
 Dirty & Pristine
 dirty is true if the user has changed the value of the control.
 <pre>Dirty? {{ myform.controls.email.dirty }}</pre>
 This would be true if the user hasn’t changed the value.
 <pre>Pristine? {{ myform.controls.email.pristine }}</pre>

 Touched & Untouched


 A controls is said to be touched if the the user focused on the control and then focused on something else.
 <pre>Touched? {{ myform.controls.email.touched }}</pre>
 touched is true of the field has been touched by the user, otherwise it’s false.
 The opposite of touched is the property untouched.

 33. What is npm and why do we need it?


 HIDE
 favorite_border
 Npm stands for Node package manager. It is an online repository and works as a package manager for
JavaScript.
 A package.json file in our application defines the dependencies that we want to download for our
application.

34. What are the benefits of using formBuilder?


HIDE
favorite_border

The FormBuilder provides syntactic sugar that shortens creating instances of a FormControl, FormGroup,


or FormArray. It reduces the amount of boilerplate needed to build complex forms.

Benefits of using form builders are:

 More flexible, but needs a lot of practice


 Handles any complex scenarios
 No data binding is done (immutable data model preferred by most developers)
 More component code and less HTML markup
 Reactive transformations can be made possible such as
 Handling a event based on a debounce time
 Handling events when the components are distinct until changed
 Adding elements dynamically
 Easier unit testing

 35. What is the observer pattern? Explain it laymen's terms.


 HIDE
 favorite_border
 Let’s take a TV as an example. All it does is waiting for new signals to come in. Then it processes them and
updates the image on the screen. It can not go ahead and send data back to the television station.
 The TV observes the signal from the television station. Whenever the station sends a signal, the TV updates.
 This does not only work between one TV and one television station. Instead, there are thousands of TV, that
are all subscribed to the station's signal.


 The Observer pattern works just the same. Usually, there is a so-called subject. The subject is the television
station from our example. On the other hand, there are also observers. These are the TVs.

 36. Can you explain the difference between ActivatedRoute and RouterState?


 HIDE
 favorite_border
 After the end of each successful navigation lifecycle, the router builds a tree of ActivatedRoute objects that
make up the current state of the router. We can access the current RouterState from anywhere in our
application using the Router service and the routerState property.
 RouterState is the current state of the router including a tree of the currently activated routes in our
application along convenience methods for traversing the route tree.

 37. What is wildcard route?


 HIDE
 favorite_border
 The route that will match against any provided URL. That's what wildcard routes are.
 The ** path in the last route is a wildcard. The router will select this route if the requested URL doesn't
match any paths for routes defined earlier in the configuration. This is useful for displaying a "404 - Not
Found" page or redirecting to another route.
 [
 {
 {
 path: ':id',
 component: ConversationCmp,
 children: [
 { path: 'messages', component: MessagesCmp },
 { path: 'messages/:id', component: MessageCmp }
 ]
 }
 ]
 }
 { path: '**', component: NotFoundComponent }
 ]
 The wildcard route will "consume" all the URL segments, so NotFoundComponent can access those via the
injected

 38. What is the use case of services?


 HIDE
 favorite_border
 The main use case of Services is to move duplicated code into a single location, acting like a Singleton. It
encourages DRY (Don't Repeat Yourself), which is a principle in Software Engineering, aimed at reducing
repitition of information or code in a multi-layered architecture.
 Services can serve as a method of interaction between an application and a data store. It also can provide
communication channels between directives, as well as any other business logic access.

39. How to create two way data binding in Angular?


HIDE
favorite_border

To set up two way data binding one must use both () and [], so:

 <component [(title)]="name"></component> is the way to go


 <component [title]="name" (titleChange)="name=$event"></component> is also
valid equivalent
 <input [(ngModel)]="userName"> this a special case for form control binding

40. How would you use http to load data from server?


HIDE
favorite_border

The HttpClient .get() method is used to make HTTP GET requests to get data from server, the syntax as follow,

First we need to import HttpClient.

import { HttpClient } from '@angular/common/http';

 Next we need to inject HttpClient


 constructor(private httpClient: HttpClient){}
 Then call HttpClient.get(ENDPOINT_URL)

get_products(){
this.httpClient.get(this.baseUrl + '/products').subscribe((res)=>{
console.log(res);
});
}

41. Which of the Angular life cycle component execution happens when a data-bound input value

updates?
HIDE
favorite_border

ngOnChanges is the life cycle hook that gets executed whenever a change happens to the data that was bound to an
input. 

42. What is the purpose of ngIf directive?


HIDE
favorite_border

Sometimes an app needs to display a view or a portion of a view only under specific circumstances. The Angular ngIf
directive inserts or removes an element based on a truthy/falsy condition. Let's take an example to display a message
if the user age is more than 18,

<p *ngIf="user.age > 18">You are not eligible for student pass!</p>

Note: Angular isn't showing and hiding the message. It is adding and removing the paragraph element from the
DOM. That improves performance, especially in the larger projects with many data bindings.

43. What is the purpose of async pipe?


HIDE
favorite_border

The AsyncPipe subscribes to an observable or promise and returns the latest value it has emitted. When a new value
is emitted, the pipe marks the component to be checked for changes. Let's take a time observable which continuously
updates the view for every 2 seconds with the current time.

@Component({
selector: 'async-observable-pipe',
template: `<div><code>observable|async</code>:
Time: {{ time | async }}</div>`
})
export class AsyncObservablePipeComponent {
time = new Observable(observer =>
setInterval(() => observer.next(new Date().toString()), 2000)
);
}

44. Why would you use renderer2 methods instead of using native element methods?
HIDE
favorite_border

Renderer2 class is an abstraction provided by Angular to manipulate elements without touching directly. Using
renderer service will provide us opportunity to be able to execute manipulations in non-DOM environments like
native mobile, desktop and web worker rendering.

45. Is NodeJS important to Angular?


HIDE
favorite_border

Angular is created in Typescript, which isn't supported by browsers. For compiling them into JavaScript, nodeJS is
required.

 Most of the Angular libraries are assigned in the form of different NPM packages. NPM(Node Package
Manager) relies more on Node.JS.
 NPM is responsible for minimizing the size of the Javascript files which basically helps in reducing
application's size.
 Angular works on the client side, while for processing on the server side you will require NodeJS.
 NodeJS works as an intermediate for hosting in Angular and transferring data to the server side.

 Think of it as a conversation between two people:

 Alex: Hey Mr. Promise! Can you run to the store down the street and get me itemA for this dish we are cooking
tonight?

 Mr. Promise: Sure thing!

 Alex: While you are doing that, I will prepare itemB (asynchronous operation). But make sure you let me know
whether you could find itemA (promise return value).

 Mr. Promise: What if you are not at home when I am back?

 Alex: In that case, send me a text message saying you are back and have the item for me (success callback). If you
don’t find it, call me immediately (failure callback).

 Mr. Promise: Sounds good! See you in a bit.

 So simply speaking, promise object is data returned by asynchronous function. It can be a resolve if the function
returned successfully or a reject if function returned an error.

47. What exactly are asynchronous data streams?


HIDE
favorite_border

Let’s take each word separately and put it into context.


 Asynchronous, in JavaScript means we can call a function and register a callback to be notified when results
are available, so we can continue with execution and avoid the Web Page from being unresponsive. This is
used for ajax calls, DOM-events, Promises, WebWorkers and WebSockets.
 Data, raw information in the form of JavaScript data types as: Number, String, Objects (Arrays, Sets, Maps).
 Streams, sequences of data made available over time. As an example, opposed to Arrays you don’t need all
the information to be present in order to start using them.

48. What is the minimum definition of a component?


HIDE
favorite_border

The absolute minimal configuration for a @Component in angular is a template.

import { Component } from '@angular/core';

@Component({
templateUrl: './minimum.component.html' // or
template: ''
})
export class MinimumComponent {}

Points to consider:

 Constructor is not required, it is auto generated


 Selector is not required, component can be accessed via router by class name
 Template is required (either template or template Url)

49. What would you have in a shared module?


 HIDE
 favorite_border
 I would put directives, pipes, components and other modules that are used throughout my application and
export them from this shared module. This way, I would not have to declare/import same
components/modules everywhere.

50. What is the difference between an observable and a promise?


HIDE
favorite_border

Both Promises and Observables provide us with abstractions that help us deal with the asynchronous nature of our
applications. However, there are important differences between the two:

 Observables can define both the setup and tear down aspects of asynchronous behavior.
 Observables are cancellable.
 Moreover, Observables can be retried using one of the retry operators provided by the API, such as retry and
retry When. On the other hand, Promises require the caller to have access to the original function that
returned the promise in order to have a retry capability.

51. What is the difference between scan() vs reduce()?


HIDE
favorite_border
 Scan will show all values emitted on source observable.
 Reduce will show only the final value emitted on source observable.

var obsScan = Observable.from([1,2,3,4,5,6]);


var count1 = obsScan.scan((acc, one) => acc + one, 0);
count1.subscribe(x => {
console.log('scan shows incremental total', x);
});

var obsReduce = Observable.from([1,2,3,4,5,6]);


var count2 = obsReduce.reduce((acc, one) => acc + one, 0);
count2.subscribe(x => {
console.log('reduce shows only total', x);
});

Output :

scan shows incremental total 1


scan shows incremental total 3
scan shows incremental total 6
scan shows incremental total 10
scan shows incremental total 15
scan shows incremental total 21
reduce shows only total 21

52. How does loadChildren property work?


HIDE
favorite_border
const routes: Routes = [
...,
{ path: 'edit', loadChildren: 'app/edit/edit.module#EditModule' },
...
]

 In the above example, loadChildren tells the router to fetch the EditModule bundle assigned to it when the
user visits '/edit' url. (To be more precise, it will ask the module loader to find and load it.)
 Router will get the router configuration from edit module.
 It merges EditModule router configuration with the main application configuration.
 Activate all the needed components.

 53. How would you set different config in different deployment server?


 HIDE
 favorite_border
 Angular CLI offers an environment feature that allows to run builds targeted at specific environments. For
instance, here is how you would run a build for production:
 ng build --configuration=production
 You can add as many environments you need here. For instance, if you need a QA build option, just add the
following entry in .angular-cli.json:
 "environments": {
 "dev": "environments/environment.ts",
 "prod": "environments/environment.prod.ts",
 "qa": "environments/environment.qa.ts"
 }
 Then all you have to do to provide a different URL for QA is to define that same property with the right value
in environment.qa.ts:
 export const environment = {
 production: false,
 serverUrl: "http://qa.server.mycompany.com"
 };
 Now that your environments are defined, how do you use those properties in your code? Easy enough, all
you have to do is import the environment object as follows:
 import {environment} from '../../environments/environment';

 @Injectable()
 export class AuthService {
 LOGIN_URL: string = environment.serverUrl + '/login' ;

 54. What's the difference between JavaScript, JScript & ECMAScript?


 HIDE
 favorite_border
 Javascript is the original name when the language was developed by Netscape.
 JScript is Microsoft's name of their own implementation.
 ECMAScript is the name of the language standard developed by ECMA, from the
original Javascript implementation.
 So, it's just one language, with different implementations.
 The implementations of Javascript and JScript differ somewhat in what they support, but each version
supports what's in the corresponding version of the ECMAScript standard. Generally you just use what's
supported a few versions back, so that it works in all the browsers that are still in use.

 55. Which lifecycle hook would you use to unsubscribe an observable?


 HIDE
 favorite_border
 ngOnDestroy(): Cleanup just before Angular destroys the directive/component.
Unsubscribe observables and detach event handlers to avoid memory leaks.
 ngOnDestroy() {
 this.subscription.unsubscribe();
 }

56. What is the difference between layout, painting and compositing(Non Angular)?


HIDE
favorite_border

 Layout. Once the browser knows which rules apply to an element it can begin to calculate how much space
it takes up and where it is on screen. The web’s layout model means that one element can affect others, for
example the width of the <body> element typically affects its children’s widths and so on all the way up
and down the tree, so the process can be quite involved for the browser.
 Paint. Painting is the process of filling in pixels. It involves drawing out text, colors, images, borders, and
shadows, essentially every visual part of the elements. The drawing is typically done onto multiple surfaces,
often called layers.
 Compositing. Since the parts of the page were drawn into potentially multiple layers they need to be drawn
to the screen in the correct order so that the page renders correctly. This is especially important for elements
that overlap another, since a mistake could result in one element appearing over the top of another
incorrectly.

 57. In routing, below tag is used to show selected route component dynamically
 HIDE
 favorite_border


 <router></router>


 <router-output></router-output>


 <router-outlet></router-outlet>

 <router-input></router-input>

 58. Choose correct form control class name which is set to true when value is modified
 HIDE
 favorite_border


 ng-valid


 ng-invalid


 ng-pending


 ng-pristine


 ng-dirty


 ng-untouched


 ng-touched

59. Below component represent “target/host” DOM element inside Directive’s constructor


HIDE
favorite_border

Element

ElementRef

Host

Target

60. What's the difference between @ViewChild and @ContentChild?


HIDE
favorite_border

Shadow DOM - is an internal DOM of your component that is defined by you (as a creator of the component) and
hidden from an end-user. For example:

@Component({
selector: 'some-component',
template: `
<h1>I am Shadow DOM!</h1>
<h2>Nice to meet you :)</h2>
<ng-content></ng-content>
`;
})
class SomeComponent { /* ... */ }

Light DOM - is a DOM that an end-user of your component supply into your component. For example:

@Component({
selector: 'another-component',
directives: [SomeComponent],
template: `
<some-component>
<h1>Hi! I am Light DOM!</h1>
<h2>So happy to see you!</h2>
</some-component>
`
})
class AnotherComponent { /* ... */ }
The difference between @ViewChildren and @ContentChildren is that @ViewChildren look for
elements in Shadow DOM while @ContentChildren look for them in Light DOM.

61. What are the various ways to implement optimizations in angular ?


HIDE
favorite_border

 Shared memory
 Lazy loading
 AOT compilation
 Css minification

 62. What is a virtual DOM and why is it used


 HIDE
 favorite_border
 The virtual DOM (VDOM) is a representation of the real DOM in the form of plain JavaScript objects. These
objects have properties to describe the real DOM nodes they represent: the node name, its attributes, and
child nodes.
 <div class="counter">
 <h1>0</h1>
 <button>-</button>
 <button>+</button>
 </div>
 The above markup's virtual DOM representation might look like this:
 {
 nodeName: "div",
 attributes: { class: "counter" },
 children: [
 {
 nodeName: "h1",
 attributes: {},
 children: [0]
 },
 {
 nodeName: "button",
 attributes: {},
 children: ["-"]
 },
 {
 nodeName: "button",
 attributes: {},
 children: ["+"]
 }
 ]
 }
 The library/framework uses the virtual DOM as a means to improve performance. When the state of an
application changes, the real DOM needs to be updated to reflect it. However, changing real DOM nodes is
costly compared to recalculating the virtual DOM. The previous virtual DOM can be compared to the new
virtual DOM very quickly in comparison.
 Once the changes between the old VDOM and new VDOM have been calculated by the diffing engine of the
framework, the real DOM can be patched efficiently in the least time possible to match the new state of the
application.

63. Will I have to transpile Angular 2’s TypeScript into normal JS?


HIDE
favorite_border

No. According to the angular2 npm package description, they’re packaging the framework 3 different ways:

1. Files in the root folder can be used with CommonJS.


2. Files under /es6 can be transpiled to ES5.
3. Files under /ts are the TypeScript source.
4. (bonus) They provide a es5build.js script to transpile ES6 to ES5 live in the browser.
5. (bonus2) They provide a sfx version (“Self-Executing bundle”) that includes SystemJS and any required
transpiler. If you went through the Angular 2 in Plain JS tutorial, that’s how that worked.

6. 64. Write a sample test case for a function in Karma-Jasmine?


7. HIDE
8. favorite_border
9. We can test a function in Karma-Jasmine as follow:
10. function addTwoNumbers(a, b){
11. return a + b;
12. }
13. Now to test this function:
14. describe('addTwoNumbers', function() {
15. it('should return sum of two numbers', function() {
16. expect(addTwoNumbers(2, 2)).toEqual(4);
17. });
18. });

You might also like