以前都知道angular2有管道這個東西,不過,由於沒有使用的必要,也就沒怎么看。
今天,做頁面,接收點擊查詢傳來的數據,然后,顯示出來。
我的做法是在本地新建一個Object對象result。然后,在數據傳過來的時候,賦值到result。
可問題出在,初始化顯示模板時,我使用了
{{ result.property }}
的數據綁定方式,但是,這種方式在 component 初始化的時候,報錯了。
說 result.property 屬性找不到。其實,想一想也明白,初始化html的時候,
result是undefined,所以找不到。
我想了其中一種方法,就是在 result 初始化的時候,用這種形式
result = { property1: 'null', property2: 'null', ...... }
但是,屬性差不多有40多個,我豈不是得寫40多次!肯定不行。
后來,想到了angular2有管道這個東西,然后,看了下文檔,覺得能用管道解決我這問題。
寫個管道判斷就行了!
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({name: 'juedeProperty'})
export class JudgePropertyPipe implements PipeTransform {
transform(obj: Object, pro: string): any {
if (obj != undefined) {
return obj[pro];
} else {
return 'null';
}
}
}
管道含義,傳入一個obj: Object類型,傳入一個pro: string類型,
如果obj為空,就返回 'null',
如果obj不為空,那么就將屬性值返回。
最后,將 JuedgePropertyPipe 導入到 module,
然后,module中的所有組件就都能使用了。
{{ result | JudgeProperty: 'property1' }}
