angular2,Pipe管道初使用。

之前都知道angular2有管道這個東西,不過,因爲沒有使用的必要,也就沒怎麼看。javascript

今天,作頁面,接收點擊查詢傳來的數據,而後,顯示出來。html

個人作法是在本地新建一個Object對象result。而後,在數據傳過來的時候,賦值到result。java

可問題出在,初始化顯示模板時,我使用了 angular2

{{ result.property }}

  的數據綁定方式,可是,這種方式在 component 初始化的時候,報錯了。spa

說 result.property 屬性找不到。其實,想想也明白,初始化html的時候,code

result是undefined,因此找不到。component

我想了其中一種方法,就是在 result 初始化的時候,用這種形式orm

result = {
  property1: 'null',
  property2: 'null',
......    
}

可是,屬性差很少有40多個,我豈不是得寫40屢次!確定不行。htm

後來,想到了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' }}
相關文章
相關標籤/搜索