異なるパイプを動的に割り当てる方法はありません。パラメータに応じて異なる動作をするパイプを作成できます
@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>
どこpipe
ですか'pipe1'
_'pipe2'