无法动态分配不同的管道。
您可以创建一个根据参数而表现不同的管道
@Pipe({
name: 'dynamicPipe'
})
class DynamicPipe implements PipeTransform {
transform(value, pipe) {
if(!value || !pipe) {
return null;
}
return pipe.transform(value);
}
}
管道可以用在什么地方
<label *ngFor="let user of users | dynamicPipe:pipe">{{user.id}}{{user.name}}, </label>
在这里pipe
是对管道类的实际实例的引用,而不是字符串。
您可以将管道注入到您的组件中,例如
class MyComponent {
constructor(private pipe1:Pipe1, private pipe2:Pipe2) {}
clickHandler() {
if(xxx) {
this.pipe = this.pipe1;
} else {
this.pipe = this.pipe2
}
}
}
您还可以将管道注入dynamicPipe
@Pipe({
name: 'dynamicPipe'
})
class DynamicPipe implements PipeTransform {
constructor(private pipe1:Pipe1, private pipe2:Pipe2) {}
transform(value, pipe) {
if(!value || !pipe) {
return null;
}
if(pipe == 'pipe1') {
return pipe1.transform(value);
}
if(pipe == 'pipe2') {
return pipe2.transform(value);
}
}
}
然后将其与管道名称一起使用
<label *ngFor="let user of users | dynamicPipe:pipe">{{user.id}}{{user.name}}, </label>
Where pipe
is 'pipe1'
or 'pipe2'