我想使用复选框对我的数据执行过滤。我有两个复选框1 - Fun,2 - 单击复选框数据时应该过滤。
component.html
<div class="type">
<label>ACTIVITY TYPE</label>
<div class="form-group">
<div class="col-xs-12">
<div class="checkbox">
<label>
<input type="checkbox" (change)="typefilter($event)" [(ngModel)]="type" name="type" #type> Learning
</label>
</div>
</div>
<div class="col-xs-12">
<div class="checkbox">
<label>
<input type="checkbox" (change)="typefilter($event)" [(ngModel)]="type" name="type" #type> Fun
</label>
</div>
</div>
</div>
</div>
component.ts
type: boolean = false;
typefilter(event){
if(event.target.checked){
this.activityService.getActivities().then(activities => this.activities = activities.filter(a => a.type == this.type));
}
}
答案 0 :(得分:2)
根据上述评论,您可以尝试:
<div class="type filters__item">
<label>ACTIVITY TYPE</label>
<div class="form-group">
<div class="col-xs-12">
<div class="checkbox">
<label>
<input type="checkbox" (change)="typefilter($event, 'Learning')" [(ngModel)]="type" name="type" #type> Learning
</label>
</div>
</div>
<div class="col-xs-12">
<div class="checkbox">
<label>
<input type="checkbox" (change)="typefilter($event, 'Fun')" [(ngModel)]="type" name="type" #type> Fun
</label>
</div>
</div>
</div>
</div>
您的组件代码:
type: String = '';
typefilter(event, typeOfActivity){
if(event.target.checked){
this.type = typeOfActivity;
this.activityService.getActivities().then(activities => this.activities = activities.filter(a => a.type == this.type));
}
}
您甚至不再需要this.type
,因为您可以在过滤器中使用typeOfActivity
,但为了清晰起见,我已将其放在那里。
答案 1 :(得分:0)
ex0dm3nt提供的答案有些变化,因为我认为它确实没有按预期工作。在两者中都具有相同的ngModel
将在单击时检查两个复选框。此外,我认为你不希望有可能同时点击这两个复选框,所以在这里我已经禁用了另一个,以防万一被点击。可能有点笨重,但应该按你的意愿工作:)
<input type="checkbox" [disabled]="fun" (change)="typefilter($event)" [(ngModel)]="learning"> Learning
<input type="checkbox" [disabled]="learning" (change)="typefilter($event)" [(ngModel)]="fun"> Fun
然后在你的TS文件中首先检查是否选中了其中一个复选框,之后是fun
或learning
,这是真的,所以你知道是否需要按&切换类型#34;乐趣&#34;或者&#34;学习&#34;
fun: boolean = false;
learning: boolean = false;
编辑:对代码进行了一些更改,因为我认为您不应该进行不必要的API调用,只需检索一次数据,然后从原始数组中切换这些值:
ngOnInit() {
this.service.getData().then(data => {
this.origActivities = data // original data to filter
this.activities = data; // displays all activities upon initialization
})
}
typefilter(event: any, filterValue: string) {
this.activities = this.origActivities;
if(event.target.checked) {
if(this.fun && !this.learning){
this.activities = this.origActivities.filter(a => a.type == filterValue);
}
else if (this.learning && !this.fun) {
this.activities = this.origActivities.filter(a => a.type == filterValue);
}
else if (this.learning && this.fun) {
this.activities = this.origActivities;
}
}
else { // user unchecks value
if(this.fun) {
this.activities = this.origActivities.filter(a => a.type == "fun");
}
else if (this.learning) {
this.activities = this.origActivities.filter(a => a.type == "learning");
}
}
}
在限定时间内,这是一个demo plunker!