Angular Questions & Answers
Angular Questions & Answers
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
Below is the list of points that describe the differences between Angular vs JQuery
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’
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()
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.
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.
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
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.
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.
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
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.
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.
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
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.
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
@Directive({
selector: '[appHighlight]'
})
export class HighlightDirective {
constructor(el: ElementRef) {
el.nativeElement.style.backgroundColor = 'yellow';
}
}
Usage
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"
}
Example of ngClass
<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.
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.
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).
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.
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
<form [formGroup]="form">
First Name <input formControlName="firstName">
Last Name <input formControlName="lastName">
</form>
{
"firstName": "FName",
"lastName": "LName",
}
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">
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:
In simple words,
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
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.
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.
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>
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.
To set up two way data binding one must use both () and [], so:
The HttpClient .get() method is used to make HTTP GET requests to get data from server, the syntax as follow,
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.
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.
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.
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.
Alex: Hey Mr. Promise! Can you run to the store down the street and get me itemA for this dish we are cooking
tonight?
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).
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).
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.
@Component({
templateUrl: './minimum.component.html' // or
template: ''
})
export class MinimumComponent {}
Points to consider:
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.
Output :
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.
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
Element
ElementRef
Host
Target
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.
Shared memory
Lazy loading
AOT compilation
Css minification
No. According to the angular2 npm package description, they’re packaging the framework 3 different ways: