angular6 自定义管道pipe(过滤器)

文章参考

管道

使用命令创建

ng generate pipe strLength

生成 str-length.pipe.ts文件,文件后缀名前面需要指明组件类型

指令内容

引入 Pipe 和 PipeTransform 从 @angular/core模块中
str-length.pipe.ts 文件

import {Pipe, PipeTransform } from '@angular/core'
@Pipe({
  name: 'strLength'
})
export class StrLengthPipe implements PipeTransform{
  transform(value: string, args?: any): any {
    return value + "----" + "huangbiao";
  }
}

@Pipe 中的name就是使用管道的名字(函数)

在ngModule中声明自定义的管道

/**
 * 告诉angular 如何组装应用
 */

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

import { AppComponent } from './app.component';
import { HeaderComponent } from './page/header/header.component';
import { NewsComponent } from './page/news/news.component';
import {StorageService} from './page/service/storage.service'
import { AppRoutingModule }     from './router/app-routing.module';
import { HttpdemoComponent } from './page/httpdemo/httpdemo.component';
import { StrLengthPipe } from './pipeCustomer/str-length.pipe';

//@NgModule 装饰器将AppModule标记为Angular 模块类(也叫做 NgModule类)
// @NgModule 接收一个元数据对象,告诉Angular 如何编译和启动应用
@NgModule({
  // 引入当前项目运行的组件,自定义组件都需要引入并且在这里声明
  // 依赖注入
  declarations: [
    AppComponent,
    HeaderComponent,
    NewsComponent,
    HttpdemoComponent,
    StrLengthPipe
  ],
  // 当前项目依赖哪些模块
  imports: [
    BrowserModule,
    HttpClientModule,
    // 如果要引入双向绑定,则需要引入FormModule
    FormsModule,
    AppRoutingModule
  ],
  // 定义服务
  providers: [
    StorageService
  ],
  // 默认启动哪个组件
  bootstrap: [AppComponent]
})

// 根模块不需要导出任何东西,因为其他组件不需要导入根模块,但是一定要写
export class AppModule { }

模板中使用

<div>
    {{title | strLength}}
</div>

注意:

  1. 不需要在组件中依赖注入管道,一旦定义,就是在模块全局范围中使用
  2. 组件的函数,就是在定义 @Pipe中的name
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值