首页 > 解决方案 > Angular 自定义管道参数

问题描述

我有一个自定义管道,我在其中传递文本和一些参数在这里我传递一个文本,如“我的名字是 %name%”,它将在我传递的参数中转换为“我的名字是 {{name}}” name:"ABC" 如何将 {{name}} 替换为我传入参数的 ABC。

import { Pipe, PipeTransform } from '@angular/core'; 
import { DomSanitizer } from '@angular/platform-browser';

@Pipe({   name: 'textTransform' }) 
export class textTransform implements PipeTransform {   
    constructor(private sanitized: DomSanitizer) {}   

    transform(value: any, args?: any[]): any {
        let val = [];
        value = value.replace(/%.*?%/g, m => { m = m.slice(1, -1); 
        return this.sanitized.bypassSecurityTrustHtml(value);   
    }
}

args 是一个键值数组,如 args[0].name="abc", args[0].age=11 所以如果字符串"My Name is {{name}} and I am {{age}} years old"应该转换为"My Name is abc and I am 10 years old"

标签: angularargumentspipe

解决方案


像这样更新转换方法语法错误

 transform(value: any, args?: any[]): any {
        const result= value.replace(/%.*?%/g, m => m.slice(1,m.length-1)); 
        return this.sanitized.bypassSecurityTrustHtml(result);   
    }

据我了解,您需要为名称传递一个新参数并进行替换

 transform(value: any, name:string): any {
        let val = [];
        value = value.replace(/%.*?%/g, m => name); 
        return this.sanitized.bypassSecurityTrustHtml(value);   
    }

模板

{{ 'My name is %name%' | name:'ABC' }} => My name is ABC

更新!

如果替换值是一个数组并且基本字符串有一个这样的位置,那就%target%去做吧

  transform(value: any, values: string[] =[]): any {
    let  result  = value;
    for(let val  of values ) {
     result = result.replace(/%.*?%/, (m) => val);
    }
    return (result);
  }

订单替换值在这里很重要

模板

{{ 'My name is %name%' | name:['ABC','15'] }} => My name is ABC 
{{ 'My name is %name% and and age %age%' | name:['ABC','15'] }} => My name is ABC and and age 15
{{ 'My name is %replace% and and age %replace%' | name:['ABC','15'] }} => My name is ABC and and age 15

演示


推荐阅读