如果用户想要通过某些不同的标准过滤他们的数据,我想要打开和关闭多个不同的管道。如何激活/停用当前在搜索中使用的管道,或者根据用户点击的按钮构建一个行为不同的管道?
例如,两个管道/过滤器看起来像这样......
//cloud.pipe.ts
import {Pipe} from '@angular/core';
import {Hero} from './hero';
@Pipe({
name: 'Cloud'
})
export class CloudPipe{
transform(value) {
if (value == null) {
return null;
}
return value.filter(hero => {
return hero.cloud === true;
});
}
}
//location.pipe.ts
import {Pipe} from '@angular/core';
import {Hero} from './hero';
import { HeroService } from './hero.service';
import { HeroesComponent } from './heroes.component';
@Pipe({
name: 'Location'
})
export class LocationPipe{
transform(value) {
if (value == null) {
return null;
}
return value.filter(hero => {
return hero.location < 500;
});
}
}
然后我想让用户切换不同的过滤器按钮并在列表中添加/删除管道。对于这样的事情,最好的方法是什么?
<!--Toggle what pipes should be used in search-->
<!--For example how can I construct the "updatePipe" function for doing this?-->
<button id="activateCloud" (click)="updatePipe()"></button>
<button id="activateLocation" (click)="updatePipe()"></button>
<!--Is it possible to have: neither of the pipes active, both at the same time or just one at the time? How can I do this?-->
<div *ngFor="let hero of heroes | Cloud | Location ></div>
我宁愿不把所有东西放在同一个管道中,因为我希望将每个管道扩展到将来做更多的事情。因此,每个管道应该“是它自己的”并且彼此独立工作,但同时必要时与其他管道一起工作。
答案 0 :(得分:0)
您可以根据要使用的参数(例如
)创建一个转发到其他管道的包装管道<div *ngFor="let hero of heroes | myPipe:'Cloud':'Location'" ></div>
@Pipe({
name: 'myPipe'
})
export class MyPipe{
locationPipe = new LocationPipe();
cloudPipe = new CloudPipe();
constructor() {
pipes = {
locationPipe: this.locationPipe,
cloudPipe: this.clouldPipe
};
}
transform(value, param1, param2) {
var result = value;
if(pram1) {
result = this.pipes[param1].transform(result);
}
if(pram2) {
result = this.pipes[param1].transform(result);
}
}
}
或者如果管道列表用作
之类的数组<div *ngFor="let hero of heroes | myPipe:['Cloud':'Location']" ></div>
@Pipe({
name: 'myPipe'
})
export class MyPipe{
locationPipe = new LocationPipe();
cloudPipe = new CloudPipe();
constructor() {
pipes = {
locationPipe: this.locationPipe,
cloudPipe: this.clouldPipe
};
}
transform(value, params) {
var result = value;
for(var p in params) {
result = this.pipes[p].transform(result);
}
}
}