Você está na página 1de 11

0.

ngOnInit

its is fucntion called when component is ready

1. ElementRef - To get reference of the element(all the possible


configuration/attribute of the element)

eg1: constructor (element:ElementRef)


{
console.log(element); // this will display all the possible
configuration/attribute of the element
}

eg2: element.nativeElement.style.color="red";

2. Custom Directive - can be used To a function or to change change a style using a


keyword.
To create a directive ng g directive DriectiveName

Eg: <input type="text" customDChangeColor>

Here customDChangeColor is directive

3. HostListener
Eg1: @HostListener('eventType') fucntionName(){
Do any thing....
}

To call a fucntion during an event from typescript itself

Eg2: @HostListener ('document:click',['$event'])

elemClicked(elem)
{
console.log(elem);
}

This eg 2 is for callig a eleClicked function where ever the clicked inside
document.

4. ViewChild

@ViewChild
Creating a reference to a tag.. Like getting the value(all attribute) from the
custom name

Eg: <input type="text" #myInputText>

@ViewChild('myInputText') inputText;

Where 'myInputText' is the viewChild Reference and inputTExt is a variable;

Later the variable can be used later for any thing.


5. ng-template

To write ur custom content and call it on ngIF

eg: < div *ngIf="condition; then temp1 else temp2">


<ng-template temp1></ng-template>
<ng-template temp2></ng-template>

6. ngIf Local Var Assignment

<div *ngIF="1==1; let newVaraible">


{{newVaraible}}

By this we can print the result of ngIF

7. Advance ngFor

<div *ngFor="let student of college; let evenprint = even">


<li *ngIf="even"></li>
</div>

By this we can print the even array or odd.

8. One way binding

HTML:

<input type="text" value="{{result}}">


<input type="text" [value]="result">

Typescript:
let result=2;

The diff between both inut tag is {{}}--> this evaluate and convert to string
if []--> this will convert to string

<input type="text (keydown)="fucntioname($event)">

This event will give all event control

9. Two way binding ang ngModel(from FormsModule Directive)


Hello {{result }}
<input type="text" [(ngModel)]="result">

10. RouterLink and routerLinkActive

routerLink
Using of href will reload the page but routerLink wont
<a routerLink="path"></a> here path is url
<a [roterLink]="custompath"></a> and here custom path is varaible

RouterLink an alternate of href in angular.


But RouterLink can be used internally . For external page go for href.

routerLinkActive

Create Routes

const appRouters: Routers =[


{
path:'login',
component: LoginComponent
}
]

<a routerLink="path" routerLinkActive="active"


[routerLinkActiveOption]="{exact:true}"></a>

[routerLinkActiveOption] will work only if the routerLink exact match

routerLinkActive="active" it will apply when the routerLink is Active. ie will


active active class for the hyperlink

11. Service
(To store value/pass value of a value across component)
Its a singale instance where it can be used to all the component under decalrtion
in module section.

To create a servie in cmd type ng generate service serviceName.


After the import the service where ever needed.
Add it in provider of the module.ts
And add it in construtor of the component it gonna be used.
If any default value on load of service add it inside constructor\
Eg: constructor()
{
this.varaible=false; (any value)
}

// eg to store the username after login so that it can be used later

12. To Create a guard (CanActivate for Router)


//it gaurd the route , like check before routes takes place

In cmd : ng generate guard AuthenticateGaurd

it will generete/add guard file into application and it will automatically add
canActivate method (which is fired before roter takes place. if it return false
router stops)

To use it add it in the route config of ur module and import it abd also add it in
provider
const appRouters: Routers =[
{
path:'login',
canActivate : [AuthenticateGaurd],
component: LoginComponent
}

inside AuthenticateGaurd file it will be like...

// the below code is auto generated


canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean> | promise <boolean>
return true;

Add a constructor in AuthenticateGaurd file


constructor(private user:userService){}

//modified from above code after service


canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean> | promise <boolean>
return fromfucntionname; (it should return boolean value)

if the value is true it will return the route

//modified for conditional routing


constructor(private user:userService, router:Router){}
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean> | promise <boolean>
this.router.navigate(['/']); // runs when failed
console.log('Not autherniticated') // runs when failed
return fromfucntionname; (it should return boolean value)

13. Advance Routing


//can be used for dynamic routing
TIP: Routes starts match from top to bottom, match comes first will match by
angular
const appRouters: Routers =[
{
path:'login',
component: LoginComponent
},
{
path:'users/:name', // a token(can be multiple token ) with url. a dynamic
data
component: UserComponent
}
]
How to make use of it..

Go to component.ts
import {ActivatedRoute} from '@angular/router';

constructor (private route: ActivedRoute)

Eg: Add console.log(route);

Now hit the url as below

localhost/user/nissan

Now in console u will get ActivatedRouter Object

inside snapshot->params we can usee name : "Nissan"


we can use it further in application

//inside component.ts
Eg: name='';
this.name=this.route.snapshot.params.name

and it html

{{name}} // this value is from url

WILD CARD ROUTE

const appRouters: Routers =[


{
path:'**',
component: NotFoundComponent // if it doenst match it goes here
}]

14. PATH MATCH

telling angular to continue to route if router matches


const appRouters: Routers =[
{
path:'user',
pathMatch : 'prefix', // this is default
component: componentName
}]

If pathMatch : 'full'

It match only if its complete consumed

15. @Input

eg: @Input() myInput;


//myinput is a variable here
// used to receive/expect a value into component from other component
and myInout value can be send from the component.

We can also rename it.

eg: @Input('myInput') myNewInput.


//myInput will be there is the component.. for access we can use myNewInput. Its
just renaming it

16. @Output/ EventEmitter

//send value from child to parent


Child Component:

import EventEmitter
eg: @OutPut() myOutput =new EventEmitter(); // will emit value to parent
this.myOutput.emit(variableName/value);

Parent Compoent :

//TS File
newfucntion(e)
{
console.log(e,'some text'); // to listen, add it where the compoent tag is called
}

//HTML File
Eg:
<app-child (myOutput)="newFucntion($event)"> // we are listing gr event

17. Angular Forms

a. Template Driven
b. Reactive Forms

a. template Driven Forms


import FormModule from @angular.
Add ngForm in form tag like <form #newForm="ngForm">
and from newForm we can take control of the form.

// to test the json format add it in html.


// {{newForm.value | json}}

Add ngModel in all the input and name of the input


ngSubmit to to submit the form data.
eg:<form #newForm="ngForm" (ngSubmit)="functionName(newForm)">

now in that argument we will be able to get the complete form data from the
argument newForm

Need Model for the user Object(create a interface)


Eg:
export Interface user{
name:string;
contact:string;
}

and import the interface in ts

userList:user[]=[];

Validation:
To diable the submit button if the form in not valid

<button [disabled]="newForm.invalid"> //when form is ivalid that button


will be disabled

a.add required attr for input fielf if its mandatory

b. Pattern Attribute
eg: pattern="add regex for the input field" //add it in html
eG: maxlength =10 //add it in html tag of the input field. not more that 10 digit
is allowed
c. Disaplay error message in input field

add a attribute like

#nameUser="ngModel"
//where nameUser is reference varaible and add it ngModel to get control

// To display error message add a tag below to the input field

<div *ngIf="nameUser.errors?.required" class="alert alert-danger">


Name is required
</div>

The above code will display error message


<div *ngIf="nameUser.errors?.tocuhed" class="alert alert-danger">
Name is required
</div>

//To display error message only after enter/ focus comes and go out/ tocuhed that
input field

<div *ngIf="nameUser?.tocuhed" class="alert alert-danger">


<div *ngIf="nameUser.errors?.required">

Name is required
</div>
</div>

// to add multiple error - required and invalid

<div *ngIf="nameUser?.tocuhed" class="alert alert-danger">


<div *ngIf="nameUser.errors?.required">

Name is required
</div>
<div *ngIf="nameUser.errors?.pattern">
Name is invalid
</div>
</div>

//error check can be added for other attribute also


eg:
<div *ngIf="nameUser.errors?.pattern || nameUser.errors?.minlength">

//Instead of ngIF hidden can also be used

Eg:

<div [hidden]="!nameUser?.hasError('minlength')">
This si rs required
</div>

//TO GET the value in Typescript

userList:user[]=[];
//add value to userList
addUSer(newForm)
{
let user:User;
user=form.value; // get value from form
this.userList.push(user); // push to userList array
}

b.REactive Form

//we wont use ngModel instead underlying APIs

import {ReactiveFormsModel} from @angular/forms //in app.ts

Interface for model for compoent value

export interface user


{
name:string;
phone:string;
}

//component.ts
import the interface to the component

and create list for the iterface

userList:user[]=[];

//to control and group component


import {FormGroup,FormControl} from @angular/forms;

FormControl : it track the class and validation status of individual tag


FormGroup :it track the class and validation status of individual of group.
//create a form group

form:FormGroup;

ngOnInit(){
//register all controls

this.form=new FormGroup({
name: new FormControl(''); //initial data
phone: new FormControl('');
})

//bind the above to html


eg:
//create for all formGroup items
<form novalidate>

<input type="text" name"">


</form>

// to bind the formGroup into html, add into form tag.

<form [formGroup]="form"> // her form is the form of ForGroup from ts

// next to add formControl


<input type="text" formControlName="name"> //same as in ts inside formGroup

//submit method
which will push to userList array
<button type="submit >

Modoify form as below


<form [formGroup]="form" (ngSubmit)="addUser(form)">

//Inside TS

addUSer(form)
{
//console.log(form.value);
}

IMPORTANT:
// we can access value internal with formGroup
// her no need to pass the value for function, that's the difference.

<form [formGroup]="form" (ngSubmit)="addUser()">

addUSer(form)
{
//console.log(this.form.value);
this.userList.push(this.form.value);
}

a. validation for reactive form

//we dont need to add it in html as in template form


//we can do it in ts itself(form control instance)
import {validator} from @angular/forms

// next add in second parameter(for validation) as below. as said before first


parameter if for initial data
Eg:
ngOnInit(){
//register all controls

this.form=new FormGroup({
name: new FormControl('',Validators.required);

})

//next add disabled in button so only if its satifies button will get enabled

<button type="submit [disabled]=form.invalid>


// till it satisfy validation it will be disabled

b. To pass mulitple validation put it isnide array

eg:

ngOnInit(){
//register all controls

this.form=new FormGroup({
name: new FormControl('',[Validators.required, validators.email]);

})

Eg: validators.email -> for email valaidator

validator.pattern('regex') - for patten

validtor.minLength(10) - min length

// to display error in html

<div *ngIf="form.get('name').hasError('required')" class="alert">


Name is required
</div>

//for touched

<div *ngIf="form.get('name').hasError('required') && form.get('name').tocuched"


class="alert">
Name is required
</div>

//for multiple error message


<div *ngIf="form.get('name').tocuhed && form.get('name').invalid" class="alert">
<div *ngIf="form.get('name')".hasError('required')">
Name is required
</div>
<div *ngIf="form.get('name')".hasError('minlength')">
less that 10 digits
</div>
</div>

TIP:

IN CSS you can use :host it like body of the page/starting tag of that page

Você também pode gostar