Men*_*cia 5 observable angular-material angular
我正在使用材料自动完成组件。
我在输入中输入的第一个字母,它按预期工作,但接下来失败了。
这显然是因为我为 设置了一个新值this.filteredUnitName:
export class ActionDetailComponent {
@Input() unitNames: Observable<string[]>;
filteredUnitNames: Observable<string[]>;
unitName: FormControl = new FormControl();
ngOnInit() {
this.filteredUnitNames = this.unitName.valueChanges
.startWith(null)
.do(val => {
if (val) {
this.filteredUnitNames = this.filter(val); // bad line
}
});
}
filter(val: string): Observable<string[]> {
return this.unitNames
.map(response => response.filter(
option => option.toLowerCase().indexOf(val.toLowerCase()) === 0
));
}
Run Code Online (Sandbox Code Playgroud)
这是我的模板:
<mat-form-field>
<input matInput placeholder="Unit name" class="form-control" [formControl]="unitName" [matAutocomplete]="auto">
<mat-autocomplete #auto="matAutocomplete">
<mat-option *ngFor="let name of filteredUnitNames | async" [value]="name">
<span>{{name}}</span>
</mat-option>
</mat-autocomplete>
</mat-form-field>
Run Code Online (Sandbox Code Playgroud)
还有另一种方法可以使其正常工作吗?
您可以使用switchMap运算符来实现这一点,因此将代码更改为以下内容:
import "rxjs/add/operator/switchMap";
ngOnInit() {
this.filteredUnitNames = this.unitName.valueChanges
.startWith(null)
.switchMap(val => {
return this.filter(val || '')
})
}
filter(val: string): string[] {
return this.unitNames
.map(response => response.filter(option => {
return option.toLowerCase().indexOf(val.toLowerCase()) === 0
}));
}
Run Code Online (Sandbox Code Playgroud)
演示:https : //plnkr.co/edit/yb4NeYTbGkwHay15R8CW? p =preview