角度2:是否设置和删除自定义管道? [英] Angular 2: Set and remove custom pipes?
问题描述
我已经创建了三个自定义管道来从服务器(ASC,DESC和Default)订购数据,它们运行良好,我希望这三个管道是否处于活动状态取决于用户的交互.
I've created three custom pipe to order data from server (ASC, DESC and Default), they work perfectly, I want that this three pipes active or not depending of the interaction of the user.
问题是,是否可以通过例如变量来更改自定义管道?.
The question is, It's posible change the custom pipe with a variable for example?.
这是我的代码...
<label *ngFor="let user of users | {{pipeOrderType}}:'name'">{{user.id}}{{user.name}}, </label>
推荐答案
无法动态分配不同的管道. 您可以根据参数创建行为不同的管道
There is no way to assign different pipes dynamically. You can create a pipe that behaves differently depending on a parameter
@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
是对管道类的实际实例的引用,而不是字符串.
您可以将管道注入到组件中,例如
while here pipe
is a reference to an actual instance of the pipe class, not a string.
You can inject pipes to your component like
class MyComponent {
constructor(private pipe1:Pipe1, private pipe2:Pipe2) {}
clickHandler() {
if(xxx) {
this.pipe = this.pipe1;
} else {
this.pipe = this.pipe2
}
}
}
您还可以将管道注入到dynamicPipe
You can also inject the pipes to the 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);
}
}
}
,然后将其与管道名称一起使用
and then use it with a pipe name
<label *ngFor="let user of users | dynamicPipe:pipe">{{user.id}}{{user.name}}, </label>
pipe
是'pipe1'
或'pipe2'
这篇关于角度2:是否设置和删除自定义管道?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!