Angular 如何在自定义管道中获取上下文

Angular 如何在自定义管道中获取上下文,angular,angular-pipe,Angular,Angular Pipe,我希望创建一个可以读取当前上下文并将其放入字符串模板的管道 @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:

我希望创建一个可以读取当前上下文并将其放入字符串模板的管道

@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
  }
}
是否有任何语法或关键字可以像“this”一样传递给我。也许$context?还是angularjs中的$scope

请忽略我是如何执行替换过程的,我只是想知道如何获得视图上下文,而不需要像“replace:this:a:b”那样逐个传入a和b,因为它可能太多而无法映射

它可以像“replace:this:$context”一样简单,在$context中我可以得到a、b和其他上下文


在我发布此问题2小时后,我了解了$implicit,但仍然不知道如何在管道中使用它。

这是您在上下文中传递的方式(此处仅适用于
attr1
):

下面是一个完整的工作示例,它打印:

output: Attr1 then x then 1
output: Attr1 then x then 2
output: Attr1 then y then 1
output: Attr1 then y then 1

您可以执行类似于
{template | replace:attr1:attr2}}
的操作,而您的管道将类似于
转换(template:string,attr1:any,attr2:any)
@harrynin谢谢您的回答,我忘记了包含假设我无法通过a和b的要求(逐个映射)“到期”对我来说太多了,无法在每一个上下文中映射
<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;
    }
}
output: Attr1 then x then 1
output: Attr1 then x then 2
output: Attr1 then y then 1
output: Attr1 then y then 1