Angular创建自定义管道

89 阅读1分钟

一、创建自定义管道

ng g p my-pipe

image.png

my-pipe.pipe.ts

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

@Pipe({
  name: 'myPipe'
})
export class MyPipePipe implements PipeTransform {

  transform(value: string, limit?: number) {
    if (!value) return null;
    let actualLimit = (limit) ? limit : 50;
    return value.substring(0, actualLimit) + '...';
  }

}

二、在全局引入管道

image.png

注意一定要export出去,否则其他组件无法使用!!!

三、在具体文件中使用管道

<div>{{testValue | myPipe:4}}</div>