我正在尝试按复选框
过滤我的数据商店sidebar.component:
<ul class="list-unstyled scrollbar">
<li *ngFor="let category of categories; let i = index">
<label class="custom-control custom-checkbox">
<input type="checkbox" name="category" id="checkbox{{ i +1 }}" value="{{category}}"
(change)="check(category, $event)" class="custom-control-input">
<small class="custom-control-indicator"></small>
<small class="custom-control-label">{{ category }}</small>
</label>
</li>
</ul>
&#13;
import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';
import { Categories } from '../shared/services/categories';
import { Feeds } from '../shared/services/feeds';
import { CategoriesService } from '../shared/services/categories.service';
import { FeedsService } from '../shared/services/feeds.service';
@Component({
selector: 'app-categories',
templateUrl: './categories.component.html',
styleUrls: ['./categories.component.scss']
})
export class CategoriesComponent implements OnInit {
categories: Categories[];
feeds: Feeds[];
myarray = [];
myobj = {
'categories': this.myarray
};
constructor(private categoriesService: CategoriesService, private feedsService: FeedsService) { }
ngOnInit() {
this.getCategories();
}
getCategories(): void {
this.categoriesService.getCategories().subscribe(categories => this.categories = categories);
}
check(category, event) {
if (event.target.checked) {
this.myarray.push(category);
this.feedsService.getFeedsfeedsByCategories([this.myobj]);
} else if (!event.target.checked) {
const index = this.myarray.indexOf(category);
this.myarray.splice(index, 1);
this.feedsService.getFeedsfeedsByCategories([this.myobj]);
}
console.log(this.myobj);
}
}
&#13;
商店feeds.component.html:
<div class="storetabContent" *ngFor="let feed of feeds">
<h3>{{ feed.feed_title }}</h3>
</div>
getFeeds(): void {
this.feedsService.getFeeds().subscribe(feeds => this.feeds = feeds);
}
我对如何检查它感到困惑,我的意思是它们处于不同的组件中,我应该如何管理状态。
我尝试使用Pipes但不起作用
我正在尝试创建像这样的复选框过滤器:
答案 0 :(得分:0)
有不同的方法来实现这一目标。其中一个是通过服务。这些是我们的假设:
data$
Observable发出数据。data$
observable并相应地更新视图。所以这被转化为:
<强> sidebar.component.ts 强>
// Method called from the template when there's a change in a checkbox
onRedCheckboxChange(evt) {
// your filterObject would look like this:
// { blue: true, red: false, green: false }
this.filterObject.red = evt.checked;
this.myService.filterData(this.filterObject);
}
我-service.service.ts 强>
import { Subject } from 'rxjs/Subject';
private data: Item[] = [];
data$: Subject<Item[]> = new Subject();
filterData(filterObject) {
const filteredData = this.data.filter(item => {
// filter your data according to the filter object
});
this.data$.next(filteredData);
}
<强> feed.component.ts 强>
ngOnInit() {
// subscribe to changes in data
this.myService.data$.subscribe(data => this.feeds = data);
}
语法可能不正确,但我希望您了解如何通过服务与过滤器有效负载通信两个组件。