Angular Docs
Angular Docs
Angular Docs
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>
<ng-template #elseCondition>
</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
url: string
toString():string }
Q4. Difference between AngularJS and Angular2?
Angualar2:
Ex: someFunction()
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.
We can declare template reference by two ways …1)using # 2)using ref (ex- ref-name)
{{#name.value}}
We create template input variable using let keyword, and it is accessible inside the element only not
outside, for outside we use var.
Employee is not accessible here, if you want to access then declare as a var.
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.
ng new myFirstAngularAPP
Npm (node package manager) is the package manager for the Node JavaScript platform.
Component
Templates
Metadata
Data Binding
Directives
Services
Dependency injection
Main.ts (start the angular application by bootstrapping root module (AppModule)
1. Bootstrapping
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)
Bootstrap: This is a root AppComponent that angular creates and inserts into the index.html host
web page.
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?
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
Angular Module is a mechanism to group components, directives, pipes and services that are related
to feature area of an angular application.
Types of NgModules:
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>.
Router-outlet specify where you want the routed component view template to be displayed.
Wildcard route is useful for invalid URL like page not found (404)
A service in angular is generally used when you need to reuse data or logic across multiple
components.
@Injectable ()
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.
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:
Easy to use
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.
Example of FormGroup:
<form [formGroup]=”profileForm”>
<label>First Name</label>
<label>Last Name</label>
</form>
Step 1. Create the instance of the FormGroup, under the formGroup create the instance of
FormControl.
profileForm: FormGroup;
Example of FormBuilder:
profileForm: FormGroup;
firstName: [‘’],
lastName: [‘’]
});
It contains the group of FormControl class and tracks the value and validity state of a group of
FormControl instances.
ngForm is a directive that crates the FormGroup instance and binds it to a form to track aggregate
form value and validation status.
</form>
<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.
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.
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();
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?
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.
ngAfterViewChecked() : gets called when component and their child component initialization is
done.
Q. what is AOT?
Ahead of time compiler converts your angular HTML and typescript code into efficient javascript
code.
Q. what Jit
Input Parameter:-
<app-parent [isFavorite] =false></app-parent>
child
@component()
class ChildComponent
@input isFavorite;
Child component
onClick()
this.change.emit(student);
Child Component
<app-child (change)=FavouriteChange($event)></app-child>
Child Component
<app-child></app-child>
addNewItem(item:string)
{
this.addNewItemEvent.Emit(item);
-----------------Pipes--
Custom Pipe:
@Pipe({name:'exponentialStrength})
transform(value: number)
return Math.pow(value)
Types of Pipe
Pure Pipe:
Impure Pipe:
ViewEncapsulation.None - Any styles applied for the component are actually globally applied.
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)
{ }
Single Page Application (SPA): means it loads only single web document, and then updates the body
content of that single document via JavaScript.
Promise
Observable
});
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);
}
}