加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

Angular 自定义管道

发布时间:2020-12-17 07:03:07 所属栏目:安全 来源:网络整理
导读:管道的作用就是将原始值进行转化处理,转换为所需要的值; 1. 新建sex-reform.pipe.ts文件 ng g pipe sex-reform 2. 编辑sex-reform.pipe.ts文件 import { Pipe,PipeTransform } form ‘@angular/core‘; //引入PipeTransform是为了继承transform方法@Pipe({

管道的作用就是将原始值进行转化处理,转换为所需要的值;


1. 新建sex-reform.pipe.ts文件

ng g pipe sex-reform

2. 编辑sex-reform.pipe.ts文件

import { Pipe,PipeTransform } form ‘@angular/core‘; //引入PipeTransform是为了继承transform方法


@Pipe({ name: ‘sexReform‘ }) //name属性值惯用小驼峰是写法,name的值为html中| 后面的名称


export class SexReformPipe implements PipeTransform {
    transform(value: string,args?: any): string {
        switch(value){
            case ‘male‘: return ‘男‘;
            case ‘female‘: return ‘女‘;
            default: return ‘雌雄同体‘;
        } 
    }
}

3. 使用demo组件中使用自定义管道

// demo.component.ts
export Class DemoComponent {
    sexValue = ‘male‘;
}

// demo.component.html
<span>{{ sexValue | sexReform }}</span>

// 浏览器输出
男
  • 同@Component({})和@NgModel({})一样,@Pipe({})代表这是一个管道,里面定义了一组元数据,用来告诉angular这个管道是如何工作的;

  • 每一个自定义管道都需要实现PipeTransform接口, transform方法用来对传入的值进行一系列处理,最后转化为需要的值后return即可;

  • transform()方法参数格式 - transform(value: string,args1: any,args2: any): value为传入的值(即为需要用此管道处理的值, | 前面的值); args 为传入的参数(?:代表可选);

  • html中使用管道格式 - {{ 数据 | 管道名 : 参数1 : 参数2 }}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读