一、模板语法简介

插值表达式

<div>Hello`name`</div>

等价于

<div[textContent]="interpolate(['Hello'],[name])"></div>

模板表达式

1.属性绑定

1.1输入属性的值为常量

<show-titletitle="SomeTitle"></show-title>

等价于

<show-title[title]="'SomeTitle'"></show-title>

1.2输入属性的值为实例属性

<show-title[title]="title"></show-title>

等价于

<show-titlebind-title="title"></show-title>

2.事件绑定

<date-picker(dateChanged)="statement()"></date-picker>

等价于

<date-pickeron-dateChanged="statement()"></date-picker>

模板引用变量

<video-player#player></video-player><button(click)="player.pause()">Pause</button>

等价于

<video-playerref-player></video-player>

双向绑定

<input[ngModel]="todo.text"(ngModelChange)="todo.text=$event">

等价于

<input[(ngModel)]="todo.text">

*与<template>

1.*ngIf

<hero-detail*ngIf="currentHero"[hero]="currentHero"></hero-detail>

最终转换为

<template[ngIf]="currentHero"><hero-detail[hero]="currentHero"></hero-detail></template>

2.*ngFor

<hero-detail*ngFor="letheroofheroes;trackBy:trackByHeroes"[hero]="hero"></hero-detail>

最终转换为

<templatengForlet-hero[ngForOf]="heroes"[ngForTrackBy]="trackByHeroes"><hero-detail[hero]="hero"></hero-detail></template>常用指令简介

NgIf

<div*ngIf="false"></div><!--neverdisplayed--><div*ngIf="a>b"></div><!--displayedifaismorethanb--><div*ngIf="str=='yes'"></div><!--displayedifstrholdsthestring"yes"--><div*ngIf="myFunc()"></div><!--displayedifmyFuncreturnsatruevalue-->

NgSwitch

有时候需要根据不同的条件,渲染不同的元素,此时我们可以使用多个 ngIf 来实现。

<divclass="container"><div*ngIf="myVar=='A'">VarisA</div><div*ngIf="myVar=='B'">VarisB</div><div*ngIf="myVar!='A'&&myVar!='B'">Varissomethingelse</div></div>

如果 myVar 的可选值多了一个 'C',就得相应增加判断逻辑:

<divclass="container"><div*ngIf="myVar=='A'">VarisA</div><div*ngIf="myVar=='B'">VarisB</div><div*ngIf="myVar=='C'">VarisC</div><div*ngIf="myVar!='A'&&myVar!='B'&&myVar!='C'">Varissomethingelse</div></div>

可以发现 Var is something else 的判断逻辑,会随着 myVar 可选值的新增,变得越来越复杂。遇到这种情景,我们可以使用 ngSwitch 指令。

<divclass="container"[ngSwitch]="myVar"><div*ngSwitchCase="'A'">VarisA</div><div*ngSwitchCase="'B'">VarisB</div<div*ngSwitchCase="'C'">VarisC</div><div*ngSwitchDefault>Varissomethingelse</div></div>

NgStyle

NgStyle 让我们可以方便得通过 Angular 表达式,设置 DOM 元素的 CSS 属性。

设置元素的背景颜色

<div[style.background-color="'yellow'"]>Usefixedyellowbackground</div>

设置元素的字体大小

<!--支持单位:px|em|%--><div><span[ngStyle]="{color:'red'}"[style.font-size.px]="fontSize">redtext</span></div>

NgStyle 支持通过键值对的形式设置 DOM 元素的样式:

<div[ngStyle]="{color:'white','background-color':'blue'}">Usesfixedwhitetextonbluebackground</div>

注意到 background-color 需要使用单引号,而 color 不需要。这其中的原因是,ng-style 要求的参数是一个 Javascript 对象,color 是一个有效的 key,而 background-color 不是一个有效的 key ,所以需要添加 ''

NgStyle 源码片段

@Directive({selector:'[ngStyle]'})exportclassNgStyleimplementsDoCheck{private_ngStyle:{[key:string]:string};private_differ:KeyValueDiffer<string,string|number>;constructor(private_differs:KeyValueDiffers,private_ngEl:ElementRef,private_renderer:Renderer){}@Input()setngStyle(v:{[key:string]:string}){//<div[ngStyle]="{color:'white','background-color':'blue'}">this._ngStyle=v;if(!this._differ&&v){this._differ=this._differs.find(v).create();}}//设置元素的样式private_setStyle(nameAndUnit:string,value:string|number):void{const[name,unit]=nameAndUnit.split('.');//截取样式名和单位value=value!=null&&unit?`${value}${unit}`:value;this._renderer.setElementStyle(this._ngEl.nativeElement,name,valueasstring);}}

NgClass

NgClass 接收一个对象字面量,对象的 key 是 CSS class 的名称,value 的值是 truthy/falsy 的值,表示是否应用该样式。

CSS Class

.bordered{border:1pxdashedblack;background-color:#eee;}

HTML

<!--Usebooleanvalue--><div[ngClass]="{bordered:false}">Thisisneverbordered</div><div[ngClass]="{bordered:true}">Thisisalwaysbordered</div><!--Usecomponentinstanceproperty--><div[ngClass]="{bordered:isBordered}">Usingobjectliteral.Border{{isBordered?"ON":"OFF"}}</div><!--Classnamescontainsdashes--><div[ngClass]="{'bordered-box':false}">Classnamescontainsdashesmustusesinglequote</div><!--Usealistofclassnames--><divclass="base"[ngClass]="['blue','round']">Thiswillalwayshaveabluebackgroundandroundcorners</div>

NgFor

NgFor 指令用来根据集合(数组) ,创建 DOM 元素,类似于 ng1ng-repeat 指令

<divclass="uilist"*ngFor="letcofcities;letnum=index"><divclass="item">{{num+1}}-{{c}}</div></div>

使用 trackBy 提高列表的性能

@Component({selector:'my-app',template:`<ul><li*ngFor="letitemofcollection;trackBy:trackByFn">`item`.`id`</li></ul><button(click)="getItems()">Refreshitems</button>`,})exportclassApp{constructor(){this.collection=[{id:1},{id:2},{id:3}];}getItems(){this.collection=this.getItemsFromServer();}getItemsFromServer(){return[{id:1},{id:2},{id:3},{id:4}];}trackByFn(index,item){returnindex;//oritem.id}}

NgNonBindable

ngNonBindable 指令用于告诉 Angular 编译器,无需编译页面中某个特定的HTML代码片段。

<divclass='ngNonBindableDemo'><spanclass="bordered">{{content}}</span><spanclass="pre"ngNonBindable>&larr;Thisiswhat{{content}}rendered</span></div>

注意事项

1.使用 [hidden] 属性控制元素的可见性

<div[hidden]="!showGreeting">Hello,there!</div>

上面的代码在通常情况下,都能正常工作。但当在对应的 DOM 元素上设置 display: flex 属性时,尽管[hidden] 对应的表达式为 true,但元素却能正常显示。对于这种特殊情况,则推荐使用 *ngIf

2.直接使用 DOM API 获取页面上的元素

@Component({selector:'my-comp',template:`<inputtype="text"/><div>Someothercontent</div>`})exportclassMyComp{constructor(el:ElementRef){el.nativeElement.querySelector('input').focus();}}

以上的代码直接通过 querySelector() 获取页面中的元素,通常不推荐使用这种方式。更好的方案是使用 @ViewChild 和模板变量,具体示例如下:

@Component({selector:'my-comp',template:`<input#myInputtype="text"/><div>Someothercontent</div>`})exportclassMyCompimplementsAfterViewInit{@ViewChild('myInput')input:ElementRef;constructor(privaterenderer:Renderer){}ngAfterViewInit(){this.renderer.invokeElementMethod(this.input.nativeElement,'focus');}}

另外值得注意的是,@ViewChild() 属性装饰器,还支持设置返回对象的类型,具体使用方式如下:

@ViewChild('myInput')myInput1:ElementRef;@ViewChild('myInput',{read:ViewContainerRef})myInput2:ViewContainerRef;

若未设置 read 属性,则默认返回的是 ElementRef 对象实例。