angular - 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"
解决方案
像这样更新转换方法语法错误
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
推荐阅读
- matlab - 如何修复“索引超过数组元素数(6)”?
- python - 在非正组件中使用不同于 Cpp 中的特征库的 python 计算特征值
- google-apps-script - 如何创建 Google 表单版本,以便我们可以在不中断生产的情况下进行开发/测试?
- javascript - 如何使用Django将值从forloop传递到模式上的url?
- javascript - JS 如何改进这个数组 -> 对象函数
- php - php dom 创建元素但自动关闭
- docker - 如何删除 Docker 映像下载失败
- python-2.7 - 如何根据列表中的值创建嵌套列表?
- javascript - 如何通过类名的第一部分选择最接近的元素?
- curl - 使用 curl 命令发布文件?