在本章中掷贾,我們將討論Angular 4中的管道。管道早先在Angular1中稱為過(guò)濾器荣茫,在Angular 2和4中稱為管道想帅。
它以整數(shù)、字符串啡莉、數(shù)組和日期作為輸入港准,以|分隔,按需要轉(zhuǎn)換格式咧欣,并在瀏覽器中顯示相同的格式浅缸。
內(nèi)置的管道
Angular 4提供了一些內(nèi)置的管道。下面列出了管道
- Lowercasepipe
- Uppercasepipe
- Datepipe
- Currencypipe
- Jsonpipe
- Percentpipe
- Decimalpipe
- Slicepipe
內(nèi)置管道的使用示例
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'Angular 4 Project!';
todaydate = new Date();
jsonval = {name:'Rox', age:'25', address:{a1:'Mumbai', a2:'Karnataka'}};
months = ["Jan", "Feb", "Mar", "April", "May", "Jun",
"July", "Aug", "Sept", "Oct", "Nov", "Dec"];
}
模板中使用
<!--The content below is only a placeholder and can be replaced.-->
<div style = "width:100%;">
<div>
<h1>Uppercase Pipe</h1>
<b>{{title | uppercase}}</b><br/>
<h1>Lowercase Pipe</h1>
<b>{{title | lowercase}}</b>
<h1>Currency Pipe</h1>
<b>{{6589.23 | currency:"USD"}}</b><br/>
<b>{{6589.23 | currency:"USD":true}}</b> //Boolean true is used to get the sign of the currency.
<h1>Date pipe</h1>
<b>{{todaydate | date:'d/M/y'}}</b><br/>
<b>{{todaydate | date:'shortTime'}}</b>
<h1>Decimal Pipe</h1>
<b>{{ 454.78787814 | number: '3.4-4' }}</b> // 3 is for main integer, 4 -4 are for integers to be displayed.
</div>
<div>
<h1>Json Pipe</h1>
<b>{{ jsonval | json }}</b>
<h1>Percent Pipe</h1>
<b>{{00.54565 | percent}}</b>
<h1>Slice Pipe</h1>
<b>{{months | slice:2:6}}</b>
// here 2 and 6 refers to the start and the end index
</div>
</div>
運(yùn)行結(jié)果
自定義管道
app.sqrt.ts
import {Pipe, PipeTransform} from '@angular/core';
@Pipe ({
name : 'sqrt'
})
export class SqrtPipe implements PipeTransform {
transform(val : number) : number {
return Math.sqrt(val);
}
}
要?jiǎng)?chuàng)建自定義管道魄咕,我們必須從Angular/core導(dǎo)入管道和管道轉(zhuǎn)換疗杉。在@Pipe指令中,我們必須給管道命名蚕礼,它將在.html文件中使用烟具。因?yàn)槲覀冋趧?chuàng)建sqrt管道,所以我們將它命名為sqrt奠蹬。
隨著我們進(jìn)一步深入朝聋,我們必須創(chuàng)建類,類名是SqrtPipe囤躁。這個(gè)類將實(shí)現(xiàn)PipeTransform冀痕。
類中定義的transform方法將以參數(shù)作為數(shù)字,并在取平方根后返回?cái)?shù)字狸演。
因?yàn)槲覀円呀?jīng)創(chuàng)建了一個(gè)新文件言蛇,所以我們需要在app.module.ts中添加相同的內(nèi)容。
<h1>自定義管道</h1>
<b>Square root of 25 is: {{25 | sqrt}}</b>
<br/>
<b>Square root of 729 is: {{729 | sqrt}}</b>
運(yùn)行結(jié)果