角度 5:如何根据 valueChanges 事件进一步过滤数据



我的最终目标是让自动完成正常工作,但我的问题是:

如何根据 valueChanges 事件进一步过滤数据?


我不仅在寻找正确的代码,还在寻找有关如何操作的解释。因为这是我第一次尝试 Angular/React 编码。

目前我有以下代码。

小玩意.html

<mat-form-field>
<input matInput placeholder="Add Gizmo"
#addGizmo
[formControl]="gizmoControl"
[matAutocomplete]="auto"
[matChipInputFor] ="gizmoChipList"
[matChipInputAddOnBlur]="addOnBlur"
(matChipInputTokenEnd)="addGizmo($event)"
/>
</mat-form-field>
<mat-form-field>
<mat-chip-list #tagChipList>
<mat-chip *ngFor="let gimzo of data.gizmos"
[selectable]="isSelectable"
color="accent"
[removable]="isRemovable" (removed)="removeGizmo(gizmo)">{{tag}}
<mat-icon matChipRemove *ngIf="isRemovable">cancel</mat-icon>
</mat-chip>
</mat-chip-list>
</mat-form-field>
<mat-autocomplete #auto="matAutocomplete" (optionSelected)="selected($event)">
<mat-option *ngFor="let gizmo of filterGizmos | async" [value]="gizmo">
{{gizmo.value}}
</mat-option>
</mat-autocomplete>

Gizmo.ts

gizmoControl = new FormControl();
private filterGizmos: Observable<Gizmo[]>;
filterGizmoData(): Observable<Gizmo[]> {
return this.dataService.findGizmos(new GizmoParameters()).map(x => x.filter(y => this.data.gizmos.includes(y.value)));
};
addGizmo(event: MatChipInputElement){
// Logic to add item
this.filterGizmos = this.filterGizmoData();
};
deleteGizmo(item: string){
//Logic to remove item 
this.filterGizmos = this.filterGizmoData();
};
ngOnInit() {    
this.dataService.getGizmo(this.gizmoId)     
.subscribe(x => {
// Logic to load data for view...
this.filterGizmos = this.filterGizmoData();
});

this.filterGizmos = this.gizmoControl.valueChanges.pipe(map(x => this.filter(x)));

}

我有一个芯片列表(数据。小玩意)显示用户已经选择了哪些 gimzos。

在输入中,用户可以选择要添加的小控件,用户可以从芯片列表中删除该小控件。 发生这种情况时,我确保从可用选项中添加/删除选定的小控件(filterGizmos)

我已经通读了 Angular 材质示例,但我似乎无法在我的代码中自动完成。

我已经在构造函数中尝试过这个:

this.filterGizmos = this.gizmoControl.valueChanges.pipe(
startWith(null),
map((name: string | null) => name ? this.filter(name) : this.filterGizmos));

但是我收到错误:

The 'this' context of type 'void' is not assignable to method's 'this' of type 'Observable<{}>'.    

我认为自动完成不起作用,因为this.filterGizmo会被this.filterGizmoData();覆盖。

代码this.filterGizmos = this.gizmoControl.valueChanges.pipe(map(x => this.filter(x)));有可能在订阅之前运行this.dataService.getGizmo(this.gizmoId),因为它将以异步方式运行。

我认为当您将数据服务中的值分配给变量并过滤该变量时,可以解决此问题,例如:

myGizmos: any[]; 
ngOnInit() {
this.dataService.getGizmo(this.gizmoId).subscribe(data => {
this.myGizmos = data;
this.filterGizmos = this.gizmoControl.valueChanges.pipe(map(x => this.filter(x)));
});
}

另请查看堆栈闪电战的样本:https://stackblitz.com/edit/angular-xqqvek

最新更新