I'm trying to use Observable
s to render two lists of items. One with the complete result, and one with a filtered result.
I have this component:
@Component({
template: `
<div *ngFor="let item of items | async">
<span>{{item.name}}</span>
</div>
<input [formControl]="filterControl" />
<div *ngFor="let item of filteredItems | async">
<span>{{item.name}}</span>
</div>
`
})
export class TestComponent implements OnInit {
private filterControl = new FormControl();
private items: Observable<Item[]>;
private filteredItems: Observable<Item[]>;
ngOnInit() {
this.items = this.dataService.get("items");
this.filteredItems = this.filterControl.valueChanges
.debounceTime(300)
.distinctUntilChanged()
.combineLatest(this.items, (filterValue, items) => {
return items.filter((item: any) => item.name.toLowerCase().indexOf(filterValue.toLowerCase()) !== -1);
});
}
}
The code will only send one http request, not one per typed filter letter, which is good. The problem is however that no filtered items will show until filterControl
emits its first value (when I type something in the input
).
Is there a way to set a default value, or a better way to solve a problem like this?
You can use the startWith
operator:
this.filteredItems = this.filterControl.valueChanges.startWith('')
This will ensure that the first value, the default empty string, will be ready