我有一个自定义管道,在其中传递文本以及一些参数 我在这里传递了一个诸如“我的名字是%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是像rgs[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"
答案 0 :(得分:1)
将转换方法更新为语法错误
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
答案 1 :(得分:0)
另一种方法是,不传递值的数组,而替换基于订单,我们可以传递属性的对象作为替换值,如果您有多个相同的地方,则更清洁的方法不受订单的限制值,如果像['abc',15,15]
transform(value: any, values: any = {}): any {
let result = value;
result = result.replace(/%.*?%/g, (m) => {
const prop = m.slice(1, m.length - 1);
return values[prop] || ''
})
return result
}
模板
{{ 'My name is %name%' | name:{name:'ABC',age : 15} }}
{{ 'My name is %name% and and age %age%' | name: {name:'ABC',age : 15} }}
%age%需要具有名称 age 的属性,并且您需要提供
'my name is %name% from %name% country'
之类的唯一名称。 因此,theis将不起作用,必须以这种方式'my name is %name% from %countryName% country'
使用像这样的对象作为参数{name:'malbarmawi' , countryName :'Turkey'}