跳到主要内容

组件相关,事件绑定,数据双向绑定,管道

一、组件相关知识

1、*ngIf

*ngIf 用来控制一个元素是否显示。

示例:

// home.component.html
<button *ngIf="isShow">按钮</button>

// home.component.ts
isShow: boolean = false;

2、*ngFor

*ngFor用来循环遍历一个数组。

示例:

// home.component.html
<ul>
<li *ngFor="let item of list;let i = index">{{i}}, {{item}}</li>
</ul>

// home.component.ts
list: Array<string> = [
'Daotin', 'lvonve', 'wenran'
];

i是索引,item是list中的每一项。

二、事件绑定

/* home.component.html */
<button (click)="add()">add</button>
<p>{{count}}</p>

/* home.component.ts */
count: number = 0;

add() {
this.count++;
}

注意:add后面一定要加()

三、数据双向绑定

/* home.component.html */
<input type="text" [(ngModel)]="txt">
<p>{{txt}}</p>

/* home.component.ts */
txt: string = '';

四、管道(过滤器)

angular中的管道就类似于vue中的过滤器的概念。

首先看看angular内置的管道:

1、日期管道

/* home.component.html */
<span>当前日期:{{time | date:"yyyy-MM-dd HH:mm:ss"}}</span>

/* home.component.ts */
time: any = new Date();

2、数字管道

/* home.component.html */
<p>{{12345.12345 | number:"4.2-4"}}</p> // 12,345.1235
//4.2-4 表示:整数至少4位,小数至少2位最多4位

/* home.component.ts */

3、大小写管道

/* home.component.html */
<p>{{"abcDEF" | uppercase}}</p>
<p>{{"abcDEF" | lowercase}}</p>

/* home.component.ts */

4、创建自定义管道

在pipes目录下创建才cny管道(用于转换一个数字为两位小数的价格)。

ng g pipe pipes/cny // 简写ng g p pipes/cny

创建的管道如下:

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
// 调用管道时的名称
name: 'cny'
})
export class CnyPipe implements PipeTransform {
/**
*
* @param value 管道之前的原始值
* @param args 管道之后的参数
*/
// transform(value: any, args?: any): any {
// return null;
// }
transform(value: number, tag: string = '¥', num: number = 2): any {
return tag + value.toFixed(num);
}
}

使用自定义的管道:

/* home.component.html */
<p>{{12345.12345 | cny : "$" : 3}}</p> // $12345.123