我希望创建一个可以读取当前上下文并将其放入我的字符串模板的管道。
@Component({
selector: 'myApp',
template: `
<input [ngModel]="template">
<div *ngFor="let a of ['x','y']">
<div *ngFor="let b of [1,2]">
<p>output: {{ template | replace:this }}<p> // replace is my custom pipe
</div>
</div>
`
})
class TextComponent {
attr1= 'Attr1';
attr2= 'Attr2';
template: string;
}
@Pipe({
name: 'replace', pure: false
})
export class ReplacecPipe implements PipeTransform {
transform(template: string, component: any) {
// perform replace process
}
}
因此,如果我将'{{attr1}}然后{{a}}然后{{b}}'放入模板中,我期望得到以下结果:
output: Attr1 then x then 1
output: Attr1 then x then 2
output: Attr1 then y then 1
output: Attr1 then y then 1
是否有任何语法或关键字让我像“ this”一样传递它。也许$ context?或$ scope在angularjs中?
[请忽略我如何执行替换过程,我只想知道如何获取视图上下文,而无需像'replace:this:a:b'一样逐一传递a和b,这可能是因为太多无法映射。
首选它可以像'replace:this:$ context'这样简单,在$ context中我可以得到a,b和其他上下文。
发布此问题2小时后,我了解了$ implicit,但仍然不知道如何在管道中使用它。
这是您在上下文中传递的方式(这里仅针对attr1
:]
<input [ngModel]="template">
<div *ngFor="let a of ['x','y']">
<div *ngFor="let b of [1,2]">
<p>output: {{ template | myReplace:attr1:a:b }}<p>
</div>
</div>
和替换管道:
export class ReplacePipe implements PipeTransform {
transform(template: string, attr: string, a: string, b:number) {
let res = template
.replace("{{attr}}", attr)
.replace("{{a}}", a)
.replace("{{b}}", b.toString());
return res;
}
}
这是一个打印的StackBlitz完整工作示例:
output: Attr1 then x then 1
output: Attr1 then x then 2
output: Attr1 then y then 1
output: Attr1 then y then 1