Angular 是由谷歌開發與維護一個開發跨平臺應用程序的框架,同時適用於手機與桌面。 管道的做用是把數據做爲輸入,而後轉換它,給出指望的輸出。html
如:前端
import { Component } from '@angular/core';
@Component({
selector: 'app-hero-birthday',
template: `<p>{{ birthday }}</p>`
})
export class HeroBirthdayComponent {
birthday = new Date(1988, 3, 15);
}
// 不使用管道時,顯示:
// Fri Apr 15 1988 00:00:00 GMT+0800 (中國標準時間)
複製代碼
使用管道後:angularjs
<p>{{ birthday | date }}</p>
// Apr 15, 1988
複製代碼
上面的案例中,使用的是data管道,來進行時間轉換,有其默認的轉換格式,咱們也能夠自定義轉換格式,只須要像data管道中傳遞參數就能夠了。api
好比咱們想要上面的信息轉換爲1998/03/15
的格式數組
<p>{{ birthday | date:"yyyy/MM/dd" }}</p>
複製代碼
Angular 內置了一些管道,好比 DatePipe
,UpperCasePipe
,LowerCasePipe
等待。 它們全均可以直接用在任何模板中。bash
要學習更多內置管道的知識,參見API 參考手冊,並用「pipe」爲關鍵詞對結果進行過濾前端框架
angular4還支持自定義管道,你能夠本身定義想要的管道。app
近期接到這樣一個需求:框架
要求在多個頁面中顯示用戶的頭像圖片,但有的用戶沒有上傳頭像的話,就須要系統根據用戶性別顯示默認的男/女頭像。angular4
固然這樣一個簡單的需求不管你是在HTML進行判斷仍是在js中判斷均可以實現。
當如果有多個頁面都須要用到的話,彷佛也是一項比較繁重的任務。
因此你能夠選擇封裝一個共用的方法在每一個頁面進行調用或者能夠嘗試自定義一個管道。
博主工做中使用的是前端框架Angularjs4
,項目總體是使用angular-cli
進行搭建的,下面介紹的是如何在angularjs
中自定義一個管道。
1.肯定需求
多個頁面顯示用戶頭像
如果頭像圖片地址不存在則判斷用戶性別
根據用戶性別顯示默認的男女頭像
如果性別和頭像圖片地址都不存在則顯示默認的人形頭像
複製代碼
2.設計管道
1.前期準備
在項目目錄src/app/common
文件夾下建立一個新文件夾pipe
,並在pipe
中建立一個comm.pipe.ts
文件。
(common文件夾是我存放一些公共組件/方法/管道的文件夾,它是一個功能的模塊,其中的全部組件/方法/管道我都會在common文件夾下的shared.module.ts中進行導出)
2.編寫comm.pipe.ts
自定義管道須要先引入@angular/core
中的Pipe
和PipeTransform
//comm.pipe.ts
import { Pipe, PipeTransform } from '@angular/core';
const sexList = ['', '男', '女'];
const uHeadImg = ['./assets/images/default_male.png', './assets/images/boy.png', './assets/images/girl.png'];
@Pipe({ name: 'portrait' })
export class Portrait implements PipeTransform {
transform(value): string {
let url = "";
if (value === '男' || value === '女') {
let idx = sexList.indexOf(value);
url = uHeadImg[idx];
} else {
url = value ? value : uHeadImg[0];
}
return url;
}
}
複製代碼
3.導出自定義管道
在shared.module.ts
中導出:
//shared.module.ts
import { NgModule } from '@angular/core';
import { Portrait } from './pipe/comm.pipe';
...
@NgModule({
imports: [
...
],
declarations: [
...
Portrait
],
exports: [
...
Portrait
]
})
export class SharedModule {
}
複製代碼
4.使用管道
因爲管道是在shared.module.ts
中導出的,所以要使用它就必須在要使用的模塊中導入
如在student
這個模塊中使用
1.首先在student.module.ts
中引用
//student.module.ts
import { NgModule } from '@angular/core';
import { SharedModule } from "./../common/shared.module";
...
import { Students } from "./students"; //students爲該模塊下的一個頁面
@NgModule({
imports: [
SharedModule,
...
],
declarations: [
Students
],
providers: [
]
})
export class StudentModule { }
複製代碼
2.在頁面中使用:
//students.component.html
<div class="uHead">
<span>學員頭像:</span>
<img src="{{studentInfo['uHeadUrl']||studentInfo.sex | portrait}}" title="頭像" alt="頭像">
</div>
複製代碼
{{}}
的方式studentInfo['uHeadUrl']||studentInfo.sex
就是傳遞給管道的參數,表示爲若是有頭像路徑則傳遞頭像路徑,沒有則傳遞性別。| potrait
表示使用名爲potrait
的管道,就是你在comm.pipe.ts
中定義的name
5.總結
在angularjs4
中使用管道總結爲這麼幾步:
1.定義一個自定義管道的ts
並引入@angular/core
中的Pipe
來編寫管道
2.將自定義管道的ts
在模塊中導出
3.要使用管道的模塊中引入管道模塊
4.html中使用的話採用如下方式:
{{ info | PipeName }} // PipeName爲你自定義的管道名稱
複製代碼