angular pipe 自定義管道

可以理解為angular中的管道(pipe)與angular1.x的過濾器(filter)一樣。

那么我們就來自定義一個管道。
新建管道

import { Pipe, PipeTransform } from '@angular/core';
@Pipe({ name: 'dataUnit' })
export class DataUnitPipe implements PipeTransform {
  transform(value: string): string {
    if(!value) {
      throw new Error('格式錯誤');
    }
    return value + `個`;
  }
} 

在pipe.module中聲明這個管道

import { NgModule } from '@angular/core';
import { DataUnitPipe } from './pipe/dataUnit.pipe'

 @NgModule({
     imports:        [],
     declarations:   [DataUnitPipe],
     exports:        [DataUnitPipe],
 })

 export class PipeModule {
   static forRoot() {
      return {
          ngModule: PipeModule,
          providers: [],
      };
   }
 } 

在app,module中引用pipe.module


app.module

在component中使用自定義好的pipe
html

<div>
    <div>
        <input type="text" #inputNum>
    </div>
    <div>
        <button (click)="onClick(inputNum.value)">點擊顯示結果</button>
    </div>
    <div>{{ myInput | dataUnit }}</div>
 </div>

ts

import { Component } from '@angular/core';
@Component({
selector: 'pipe-app',
templateUrl: './pipe.component.html',
})
export class PipeAppComponent {
  myInput = 0;
  onClick (value){
      this.myInput = value; 
  }
}

界面輸出:


拋出錯誤
正常顯示
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容