自訂Pipe


程式碼範例:

1.在終端機進入/src/app 2.利用Angular CLI建立Pipe元件,在終端機輸入指令ng g p substr-pipe 3.建立的Pipe元件如下:

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

@Pipe({
  name: 'substrPipe'
})
export class SubstrPipePipe implements PipeTransform {

  transform(value: any, args?: any): any {
    return null;
  }

}

4.AppModual會自動import Pipe元件,並且在declarations宣告

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';

import { AppComponent } from './app.component';
import { SubstrPipePipe } from './substr-pipe.pipe';

@NgModule({
  declarations: [
    AppComponent,
    SubstrPipePipe
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

5.改寫自訂Pipe元件中的transform(),使其回傳substring後的傳入字串

transform(value: string, start?: number, end?: number): string {
  var startIndex = start == undefined ? 0 : start;
  var endIndex = end == undefined ? value.length : end;
  return value.substr(startIndex, endIndex);}

6.修改app.component.html如下:

<h1>
{{title|substrPipe:0:3}}
<h1>

7.頁面文字由app works!變為app

results matching ""

    No results matching ""