内置指令的使用
对于指令的个人理解是,将一些经常会用到的方法(包括对数据的处理、对对象的绑定)进行封装起来,从而使开发更加便利更加简洁,也是项目模块化的一种内在的表现形式。
表1.指令的相关问题
问题 | 答案 |
---|---|
什么是内置指令 | 负责在多个不同内容片段之间进行选择以及重复内容 |
作用 | 根据数据来调整要显示的内容并且 |
如何使用 | 在HTML元素中使用 |
使用时需要注意的问题 | 一些指令(ngIf和ngFor)必须带有星号前缀,而其他指令(ngClass、ngStyle和ngSwitch)必须用方括号括起来。 |
怎么看待 | 虽然可以编写自定义的指令,但内置指令是精心编写、全面测试、长期完善的结果,内置指令始终是最好的选择。 |
内置指令
指令名称 | 功能和描述 |
---|---|
ngIf | ngIf是最简单的指令了,也就是当表达式为true时,将HTML片段包含在文档中,false时就不包含 |
ngSwitch | 类似于JavaScript的switch语句,如果ngSwitch表达式的求值结果与指定结果相同,那么该元素和内容就会包含在HTML文档中,相应的如果不同就不包含。 |
ngFor | 提供相当于foreach循环的模板,并且能够遍历对象集合。 |
ngTemplateOulet | 当需要在不同的地方生成相同内容并且希望避免重复操作时,ngTemplateOulet会很有用。 |
ngClass | ngClass是一种灵活的属性绑定,基于表达式返回的数据类型改变行为方式。 |
ngStyle | 可以使用映射对象来设置多个样式属性[ngStyle=“getStyles(number)”] |
1.ngFor、ngSwitch、ngClass、ngIf的使用
app.component.html
<h3 class="bg-primary p-a-1">{{getName()}}'s 任务清单</h3>
<div class="m-t-1 m-b-1">
<input class="form-control" #todoText />
<button class="btn btn-primary m-t-1" (click)="addItem(todoText.value)">
添加事情
</button>
</div>
<table class="table table-striped table-bordered">
<thead>
<tr><th></th><th>事情描述</th><th>是否完成</th></tr>
</thead>
<tbody>
<tr *ngFor="let item of getTodoItems(); let i = index">
<td>{{i + 1}}</td>
<td>{{item.action}}</td>
<td><input type="checkbox" [(ngModel)]="item.done" /></td>
<td [ngSwitch]="item.done">
<span *ngSwitchCase="true">Yes</span>
<span *ngSwitchDefault="">No</span>
</td>
</tr>
</tbody>
</table>
<div [ngClass]="'btn btn-danger'">输入</div>
<p *ngIf="2<3">在model里面要做的事超过三件</p>
<p *ngIf="2>3">在model里面要做的事不超过三件</p>
app.component.ts
import { Component } from "@angular/core";
import { Model, TodoItem } from "./model";
@Component({
selector: "todo-app",
templateUrl: "app.component.html"
})
export class AppComponent {
model = new Model();
getName() {
return this.model.user;
}
getTodoItems() {
return this.model.items.filter(item => !item.done);
}
addItem(newItem) {
if (newItem != "") {
this.model.items.push(new TodoItem(newItem, false));
}
}
}
model.ts
export class Model {
user;
items;
constructor() {
this.user = "William";
this.items = [new TodoItem("买花", false),
new TodoItem("去干洗店拿衣服", false),
new TodoItem("挪车", false),
new TodoItem("给Nina打电话", false)]
}
}
export class TodoItem {
action;
done;
constructor(action, done) {
this.action = action;
this.done = done;
}
}
以上代码运行结果:
2.ngTemplateOulet的使用
<ng-template #titleTemplate let-text="title">
<h4 class="p-a-1 bg-danger">{{text}}</h4>
</ng-template>
<ng-template [ngTemplateOutlet]="titleTemplate" [ngTemplateOutletContext]="{title: '页头'}">
</ng-template>
<ng-template [ngTemplateOutlet]="titleTemplate" [ngTemplateOutletContext]="{title: '页脚'}">
</ng-template>