Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Angular Docs

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 16

Q1. What is ng-template?

If you add ng-template tag to your template, it and everything inside it will be replaced by comment.
It is basically used with structural directive (*ngIf, *ngFor, *ngSwitch).

Ex: - Suppose you have a div and you want to render it based on if else condition.

<div *ngIf=”someConditon else elseCondition”>

<p>Display when if block returns true.

</div>

<ng-template #elseCondition>

<P>Display with else condition.</p>

</ng-template>

Q2. CanActivate ?

CanActivate is an interface that has a method CanActivate . If the guard returns true navigation
continues if guard return false, navigation is cancelled.

export class AuthGuard implements CanActivate {

  constructor(private auth:AuthService,private router:Router) { }
  path: ActivatedRouteSnapshot[];
  route: ActivatedRouteSnapshot;
 
  canActivate(){
   return this.auth.user$.map(user=>{
      if(user) return true;
      
     this.router.navigate(['/login']);
     return false;
    })
  }
}

Types of Guard

CanActivate : Check to see if user can visit the route.

Q3. What is RouterStateSnapshot?

Represents the state of the router at a moment time.

Interface RouterSateSnahpshoet extends Tree{

url: string

toString():string }
Q4. Difference between AngularJS and Angular2?

Angualar2:

1. Is helpful for developing mobile application.


2. Loading time is faster in angular2, as there is dynamic loading feature.
3. TypeScript support in angular 2, we have to write less code.
4.

Q5. Var vs Let vs Const?

 Var and Let variable can be changed.


 Var is scoped to the nearest function block and let is scoped to the nearest closing block.

Ex: someFunction()

For (let i=0;i<10;i++)

// I is only accessible only here

// I is not accessible here.( by declaring I as var you can access here).

 By using Var you can redeclare the same variable in the same scope. On the other hand
let will not allow the same.

Const : Once you declare variable as a const you can’t change. Scope of const variable same as let ,
it is accessible to the nearest closing block.

Q6. What is template reference variable?

By using template reference variable, you can access DOM properties.

We can declare template reference by two ways …1)using # 2)using ref (ex- ref-name)

Ex : <input type=”text” value=”ashish” #name/>

{{#name.value}}

Q6. What is Template input variable?

We create template input variable using let keyword, and it is accessible inside the element only not
outside, for outside we use var.

Ex : <div *ngFor=”let employee of employees”>

Employee is accessible only here


</div>

Employee is not accessible here, if you want to access then declare as a var.

Q7. What is Angular CLI, and how to update Angular CLI?

Angular CLI (Command line interface) is a set of tools that is used to initialize, develop, generate
files, and test and maintain the angular application.

To install angular CLI globally we use,

npm install -g@angular/cli

ng new myFirstAngularAPP

Q8. What is npm?

Npm (node package manager) is the package manager for the Node JavaScript platform.

Npm install packagename --save

Q9. Main building block of an angular application.

 Component
 Templates
 Metadata
 Data Binding
 Directives
 Services
 Dependency injection
Main.ts (start the angular application by bootstrapping root module (AppModule)

1. Bootstrapping

2. Imports (when we need some


6. Injectors features from other module)
5. Providers
(Creates
(Stores the
the NgModule
blueprint of 3. Exports (when we want to
instance of
services) share some features to other
services)
module)

4. Declaration

Dependency Injection Event binding (if you want to pass the data from template
to component)
When component require a
Component(AppCo
Service. Template
mponent)

Property Binding (if you want to pass the data from


component to template)

Bootstrap: This is a root AppComponent that angular creates and inserts into the index.html host
web page.

Bootstrapping: Bootstrapping is a technique of initializing or loading of our angular application.

Step1. Main.ts file start the angular application by bootstrapping root module (appModule).

Step2. NgModule get called, and under Ngmodule we have imports when we need some features of
other module, and there is exports if you want to share some features to other module, and there is
declaration in declarations we have component so component and template makes the view and
component shares the data to the template through property binding , and template shares the data
to component through event binding and there is a provider section under the provider we have list
of services if component needs the data from the server then it goes to the injector, injector creates
the instances of the services and shares the data to the component.
Q10. What are components in Angular?

A component is a class with template and decorator.

Template: Defines the user interface.

Class: Contains the code required for template.

Decorator: Adds the metadata to the class. A class becomes an angular component, when it is
decorated with the component decorator.

@component({

Selector:’my-firstcomponent’,

Template:`<h1>Hello {{Name}}>/h1>`

})

Class MyFirstComponent

Name: string =” Angular”;

Q11. What are NgModules?

NgModules is a class that is decorated with @NgModule decorator.

Angular Module is a mechanism to group components, directives, pipes and services that are related
to feature area of an angular application.

Ng g m employee/employee –flat -m app

Types of NgModules:

1. Features Module: for the purpose of organizing the application code.


For example, if you are building an application to manage employees, you might have the
following features in your application.
Employee features, Login Features, Report Features so we create module for each features
area. These modules are called features module.
2. Routing Module: Routing module is used to manage routes.
For example, we have three feature modules for separation of concerns and ease of
maintenance, here is what we want to do.
Include all the application level routes like Home, Empty Path, Wild card routes in the
AppRoutingModule.
Include all employee features module routes like List, Create and Edit in a separate
EmployeeRouting Module.
3. Shared Module: Shared module contains all the commonly used directives, pipes and
components that we want to share with other modules that import this shared module.
- Shared module should not have any providers.
4. Service Module: the modules that only contains services and providers.
5. Widget Module: The third-party UI component libraries are widget modules.

Q12. How angular Routing works?

When we hit the URL,

Step 1: parse the URL.

Step 1: When the URL changes angular router looks for the corresponding route in the route
configuration. (url: localhost:4200/home).

Step 2: we configure component along with path, so angular router knows which component needs
to be render once component picked.

Step 3: then angular router looks for the <router-outlet> directive, then the component is then
displayed at the location where we have the <router-outlet>.

/- divide the URL segments.

: - a colon specifies a named router outlet.

Q13. What is router-outlet?

Router-outlet specify where you want the routed component view template to be displayed.

Q14. What is wildcard route?

Wildcard route is useful for invalid URL like page not found (404)

{path:’**’, component: PageNotFound}

Q15. What is service?

A service in angular is generally used when you need to reuse data or logic across multiple
components.

@Injectable ()

Export class EmployeeService{

getEmployee():IEmployee[]{

return[{},{}]

@Injectable () decorator is used to inject other dependencies into the service, you may remove the
@injectable() if your service is not using any dependencies.

Q16. What is dependency injection?


It is a coding pattern in which a class receives its dependencies from external sources rather than
creating them itself.

Q17. What is template driven form?

Template driven forms are the simple forms which can be used to develop forms. These are
template driven as everything that we are going to use in an application is defined into the template
along with the component.

Prerequisite:

We need to import FormsModule in an application module file (app.module.ts)

Features and limitation:

Easy to use

Suitable for simple form fails for complex scenarios.

Q18. What is model-driven forms (Reactive forms)?

Reactive forms are forms where we define the structure of the form in the component class.it is use
for creating complex forms as well as creating dynamic forms.

Prerequisite.

Import ReactiveFormsModule.

There are two ways to create Reactive forms:

Using FormGroup and FormBuilder

Example of FormGroup:

<form [formGroup]=”profileForm”>

<label>First Name</label>

<input type=”text” formControlName=”firstName”/>

<label>Last Name</label>

<input type=”text” formControlName=”lastName”/>

</form>

Step 1. Create the instance of the FormGroup, under the formGroup create the instance of
FormControl.

profileForm: FormGroup;

profileForm: new FormGroup({

firstName: new FormControl(‘’);

lastName: new FormControl(‘’);


});

Example of FormBuilder:

To avoid creating FormControl instances manually we use FormBuilder.

Import the formBuilder class.

Inject the formBuilder service.

Generate the formsContents.

Constructor (private fb: FormBuilder) {}

profileForm: FormGroup;

this. ProfileForm= this.fb. group ({

firstName: [‘’],

lastName: [‘’]

});

Q19. What is FormGroup?

It contains the group of FormControl class and tracks the value and validity state of a group of
FormControl instances.

Q20. What is FormControl?

Tracks the value and validation status of an individual form control.

Q21. What is Difference between [ngModel] and [(ngModel)]

[ngModel] it is used for Property binding (one way binding).

[(ngModel)] it is used for two-way data binding.

Q22. What is ngForm?

ngForm is a directive that crates the FormGroup instance and binds it to a form to track aggregate
form value and validation status.

<form #f=”ngForm” (ngSubmit)=”onSubmit(f.value)”>

</form>

Q23. What is ngModelGroup ?

ngModelGroup is a directive that is used as a child in <form> tag to create subgroups.

<form #f=”ngForm” (ngSubmit)=”onSubmit(f.value)”>

<div ngModelGroup=”personalDetails”>

</div>

</form>
Q24. What is ngModel?

When we add ngModel directive to the control, all the inputs are registered in the ngForm.

Q25. What is Transpiling in Angular?

Transpiling : code from high level language get converted to another high level language.

Q26.

BrowserModule: The browser module is used when you want to run your application in a browser.
The browsermdule is imported from @angular/platform-browser.

CommonModule: Then common module is used when we want to use directive -ngIF, ngFor and so
on. Imported from @angular/common.

FormsModule: FormsModule is used to create template driven form. Imported from


@angular/forms.

ReactiveFormsModule: is used when we want to build model-driven i.e. reactive form.

RouterModule: is used when we want to use routing, RouterLink,forRoot and forChild.

Q27. What is @ngModule?

@ngModule decorators identifies appmodule as NgModule class.

Q28. What is setValue() and patchValue()?

Both setValue() and patchValue() set the value of a control in a formgroup. If you want to set the
value of all form controls use set value, use patch value when you don’t want to set the value of all
form controls.

This.formName.patchvalue();this.formName.setValue();

Q29. What is FormArray?

A FormArray aggregates the values of each child controls into an array. It is useful when we don’t
know how many controls will be present within the group, like dynamic forms.
<section>
<p>Any special requests?</p>
<ul formArrayName="specialRequests">
<li *ngFor="let item of orderForm.controls.specialRequests.controls; let i = index">
<input type="text" formControlName="{{i}}">
<button type="button" title="Remove Request" (click)="onRemoveSpecialRequest(i)">Remove</button>
</li>
</ul>
<button type="button" (click)="onAddSpecialRequest()">
Add a Request
</button>
</section>
constructor () {
this.orderForm = new FormGroup({
firstName: new FormControl('Nancy', Validators.minLength(2)),
lastName: new FormControl('Drew'),
specialRequests: new FormArray([
new FormControl(null)
])
});
}

onSubmitForm () {
console.log(this.orderForm.value);
}

onAddSpecialRequest () {
this.orderForm.controls
.specialRequests.push(new FormControl(null));
}

onRemoveSpecialRequest (index) {
this.orderForm.controls['specialRequests'].removeAt(index);
}
Q20. Angular life cycle hooks?

A component instance has a lifecycle that starts when component instantiate.

ngOnChanges() : called when one or more data-bound input properties change.

ngOnInit(): called after ngOnChnages() for the first time. It commonly used for component
initialization and retrieving data from data base.

ngDoCheck(): Called

immediately after ngOnChnages() on every change detection run, and immediately after ngOnInit()
on the first time. To monitor changes that occur where ngOnChanges() won’t catch them.

ngAfterContentInit(): Called immediately after initialization of ngContent in a component.

ngAfterContentChecked(): gets executed when any change detected under ng content.

ngAfterViewInit() : gets called when component initialization is done.

ngAfterViewChecked() : gets called when component and their child component initialization is
done.

ngOnDestroy(): gets executed before component get destroyed. For unsubscrible()

Q. what is AOT?

Ahead of time compiler converts your angular HTML and typescript code into efficient javascript
code.

It has already complied.

Q. what Jit

Compile before displaying in the browser.

Input Parameter:-
<app-parent [isFavorite] =false></app-parent>

child

@component()

class ChildComponent

@input isFavorite;

-----------------Out put parameter----------------------

Child component

@Output change= new EventEmitter();

onClick()

this.change.emit(student);

Child Component

<app-child (change)=FavouriteChange($event)></app-child>

<app-parent (addNewItemEvent)="addItem($event)"> </app-parent>

Child Component

<app-child></app-child>

@output() addNewItemEvent= new EventEmitter<string>();

addNewItem(item:string)
{

this.addNewItemEvent.Emit(item);

-----------------Pipes--

Is used to transform the data.

DatePipe, UpperCasePipe, LowerCasePipe, CurrencyPipe, DeciamlPipe, PercentPipe

ex - <P> Ram birthday is {{ birthday | date:"MM/dd/yy" | uppercase}}

Custom Pipe:

import {Pipe,PipeTransForm} from '@angular/core;

@Pipe({name:'exponentialStrength})

export class CustomPipe implements PipeTransForm

transform(value: number)

return Math.pow(value)

Types of Pipe

Pure and Impure Pipes

Pure Pipe:

 Executed only when a pure change to the input value is detected.


 A pure change is either a change to a primitive input value (String, Number, Boolean) or a
changed object reference (Array, date, Object).
 Is fast.
 A pure pipe is not executed if the input to the pipe is an object and only the property values
of the object change but not the reference.
 Pure is default.

Impure Pipe:

Impure pipe is processed on every change. Avoid to create impure pipe.


=================

ViewEncapsulation.None - Any styles applied for the component are actually globally applied.

ViewEncapsulation.Emulated - Applied to that component view.

ViewEncapsulation.ShadowDOM -The Shadow DOM is a scoped sub-tree of the DOM.

Interceptor

Interceptor is a special angular service that can be used to intercept all the request and response
calls and modify them according to our requirement.

import {
Injectable }
from
'@angular/core';
import { HttpInterceptor } from '@angular/common/http';
import { HttpRequest } from '@angular/common/http';
import { Observable } from 'rxjs';
import { HttpHandler } from '@angular/common/http';
import { HttpEvent } from '@angular/common/http';
import { HttpResponse } from '@angular/common/http';
import { Router } from '@angular/router';
import { FacadeService } from '../service/facade.service';
import { map } from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class InterceptorService implements HttpInterceptor {
token: string;
omitCalls = ['auth'];
skipInterceptor = false;
constructor(private router: Router, private facadeService: FacadeService)
{ }

intercept(req: HttpRequest<any>, next: HttpHandler):


Observable<HttpEvent<any>> {
this.omitCalls.forEach(api => {
if (req.url.includes(api)) {
this.skipInterceptor = true;
}
});
this.token = this.facadeService.getUserToken();
if (this.token || this.skipInterceptor) {
const tokenizedReq = req.clone({ headers:
req.headers.set('Authorization', 'Bearer ' + this.token) });
return next.handle(tokenizedReq).pipe(map((event: HttpEvent<any>) =>
{
if (event instanceof HttpResponse) {
if (event.status === 401) {
this.facadeService.userLoggedOut();
this.router.navigateByUrl('core/login');
}
}
return event;
}));
} else {
this.facadeService.userLoggedOut();
this.router.navigateByUrl('core/login');
}
return next.handle(req);
}
}

Single Page Application (SPA): means it loads only single web document, and then updates the body
content of that single document via JavaScript.

Difference between promise and Observable

Promise

 It call as soon as it defined it. (eager)


 It emits single value.
 You can’t cancel the promise.
 Const promise = new Promise (resolve=>{
Console. Log (‘Promise call ….);
setTimeout(()=>{
resolve (‘ Promise working’);
},1000);
 });
Promise.then(result=> console.log(result));

Observable

 To call it we have to listen it. (Lazy)


 It can emits multiple values.
 We can use operator here. (filter,pipe, map)
 You can unsubscribe the observable.
Const observable = new Observable (sub=>{
Console.log(‘Observable called’);
setTimeout(()=>{
sub.next(‘observale working’);
},1000);

});
Observable.subscribe (result=> console.log(result));

Closures in JavaScript

Closure is a function that references variables in the outer scope from its inner scope.

 @property {boolean} $untouched True if control has not lost focus yet.
 @property {boolean} $touched True if control has lost focus.
 @property {boolean} $pristine True if user has not interacted with the control yet.
 @property {boolean} $dirty True if user has already interacted with the control.

Subject example :
import { Injectable } from '@angular/core';
import { BehaviorSubject, Subject } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class DataServiceService {
SharingData = new Subject();//subject
constructor() { }
//update value
changeDataSubject(data: any) {
this.SharingData.next(data.value);
}
}

You might also like