angular指令

一.内置指令

1.ngClass:在angular中,通过ngClass指令,可以同时添加或者移除多个类。

2.ngStyle: 使用ngStyle指令,可以给模板元素设置多个内联样式。

3.ngIf: 使用ngIf指令能够控制元素是否显示,并且如果其值为false的话,那么会从DOM树移除。

4.ngSwitch: ngSwitch指令需要和ngSwitchCase指令和ngSwitchDefault指令搭配使用。

5.ngFor:使用ngFor来展示列表数据;同时也可以获取到遍历索引;对于包含复杂列表的使用场景来说,使用普通的ngFor来渲染列表数据的话那么会出现明显的性能问题,此时应该配合使用trackBy来提升性能。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
// app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {

contractName = 'hahahai';

setClasses() {
let classes = {
red: true,
font14: true,
title: true
};
return classes;
},

setStyles() {
let styles = {
'color': true ? 'red' : 'yellow',
'font-size': true ? '14px' : '16px',
'font-weight': true ? 'bold' : 'normal'
};
return styles;
}
}

// app.component.html
<div>
<h1 [ngClass]="setClasses()">angular</h1>
<h1 [ngStyle]="setStyles()">angular</h1>

<span [ngSwitch]="contractName">
<span *ngSwitchCase="'timcook'">timcook</span>
<span *ngSwitchCase="'billgates'">billgates</span>
<span *ngSwitchCase="'hahahai'">hahahai</span>
<span *ngSwitchDefault>弄那么</span>
</span>
</div>