angular自定義管道【pipe】


鏈接:https://juejin.im/post/58db5b55128fe1006cdf0bb3

angular中,管道的使用

管道一般適用於Mustache語法 的雙向數據內, eg{{item |json}}  該例子采用了內置的JsonPipe管道。

若要帶參數 則{{item |slice:0:4}  管道后面冒號跟隨的就是參數

多重管道如何調用 {{item |slice:0:4|uppercase}}

 

如何書寫一個自定義管道

1 自定義管道必須依賴這2個

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

2 // 管道裝飾符 ,name就是管道名稱

  @Pipe ({name: 'name'})

 

3 export class PipeNamePipe implements PipeTransform {

  // value: 傳入的值

  // ... args: 參數集合(用了...拓展符),會把數組內的值依次作為參數傳入 參數可改成常規的寫法(value: any ,start: number, end: number)

  transform(value: any,  ...args:any[]) : any {}

}

例1 實現一個切割字符串然后拼接...的管道【用於渲染數據過長截取】

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

@Pipe( {

  name: 'SliceStr'

 })

export class SliceStrPipe implements PipeTransform {

  

/** * 截圖字符串字符 * option(start,end,[+str]) */ // start和end及extraStr后面都跟隨了一個問好,代表這個為可選參數而不是必選的 // 功能就是給出截圖的啟示,然后是否拼接你自定義的字符串(...)等
  transform(value: string, start?: number, end?: number, extraStr: string) :string {
    if (value) {
      if (typeof start === 'number' && typeof end === 'number') {
        if (value.length > end && extraStr && typeof extraStr === 'string') {
          return value.slice(start, end) + extraStr,toString();
        } else {
          return value.slice(start, end);
        }
      } else {
        return value.slice(start, end)
      }
    } else {
      return value;
    }

}

 

模仿angular中的 keyvalue管道:

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

/*

 Convert Object to array of keys.

*/

@Pipe({

  name: 'appProperties'

})

export class PropertiesPipe implements PipeTransform {

  transform(value: {}): string[] {

    if (!value) {

      return [];

    }

    return Object.keys(value);

  }

}

 

在模板中使用: <div *ngFor="let property of response |appProperies>

        <div *ngFor="let item of response[property]"> {{item.dosomething}}</div>

      </div>

 

如何是一個自定義管道生效

// 功能管道 , 單一引入生效

import { SliceStrPipe } from './SliceStr/slice-str.pipe';

@NgModule ( {

  imports: [CommonModule],'

  declarations: [SliceStrPipe], //  管道生效必須放到declarations里面

})

// 模塊引入

寫一組管道,放到自定義模塊中,最后導出,然后在其他模塊引入這個模塊就能直接使用

import ..........


const pipe = [
IsCitizenIDPipe,
IsEmailPipe,
IsEnhancePasswordPipe,
IsFixedPhonePipe,
IsLicensePipe,
IsMobilePhonePipe,
IsNormalPasswordPipe,
IsNumberPipe,
IsUsernamePipe,
SliceStrPipe,
TimeDifferencePipe,
TransDatePipe,
ThousandSeparationPipe
];

@NgModule( {
imports: [
CommonModule
],
declarations: [
MitPipeComponent,
...pipe,
],
exports: [ ...pipe ],
schemas: [ CUSTOM_ELEMENTS_SCHEMA ]
})
export class MitPipeModule { }

 

// ----- 引入module

// 管道 -- 把MitPipeModule丟到imports里面就行了
import { MitPipeModule } from '../../../../../widgets/mit-pipe/mit-pipe.module';

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM