在angular中有很多的指令,其中ng开头的指令是我们常用的.
- NgIf
<div *ngIf="a>b"</div> <!--当a>b的时候显示-->
<div *ngIf="str=='yes'"></div> <当str等于yes的时候显示-->
<div *ngIf="myFunc()"></div><!--当函数返回true的时候-->
- NgSwitch
<div class='container' [ngSwitch]="myVar">
<div *ngSwitchCase="'A'">Var is A</div>
<div *ngSwitchCase="'B'">Var is B</div>
<div *ngSwitchCase="'C'">Var is C</div>
<div *ngSwitchDefault>Var is something else</div>
</div>
- NgStyle 作用:让我们可以方便得通过表达式,设置DOM元素的CSS熟悉
<div [ngStyle]="{color:'white','background-color:'blue'}>
Uses fixed white text on blue background
</div>
- NgClass 接收一个对象字面量
对象的 key 是 CSS Class 的名称 value 的值是truthy/falsy的值,表示是否应用该样式
CSS 样式
.bordered{
border:1px dashed black;
background-color:#eee;
}
HTML
<div [ngClass]="{bordered:false}">This is never bordered</div>
<div [ngClass]="{bordered:true}"> This is always bordered</div>
- NgFor :渲染的时候会用到
//定义数组
public list:any[]=['我是第一个新闻',22222,'我是第三个新闻'];
//遍历list数组中的每一个项,并且显示出来
<ol>
<li *ngFor="left item of list>
{{item}}
</li>
</ol>
数组中还可以包含对象:
public userlist:any[]=[{
username:'张三',
age:20
},{
username:'李四',
age:21
}];
//渲染数组中的内容:
<ul>
<li *ngFor="let item of userlist let key=index;">
<span *ngIf="key==1" class="red"> {{key}}---{{item.username}}<span>
<span *ngIf="key!=1">{{key}}----{{item.username}}<span>
</li>
</ul>