【发布时间】:2020-01-18 05:55:25
【问题描述】:
我希望county 字段具有自动完成选项,因为列表中的项目太多以至于用户有时会因滚动和滚动而受到冒犯。
目前代码有两个问题。
首先是输入框看起来不错,但是无论我输入什么,它都不会从列表中过滤
其次,我的county 对象有两个属性countyId 和countyName,当我从列表中选择县时,它显示countyId 而不是名称,因为它与Id 绑定。如何更改它以显示名称并仍与 Id 绑定,因为我需要将 id 发送到服务器。
这是我的html
<mat-form-field appearance="outline" fxFlex="50" class="pr-4">
<!-- <mat-label>County</mat-label> -->
<input type="text" placeholder="select county" name="" matInput [formControl]="countyId" [matAutocomplete]="auto">
<mat-autocomplete autoActiveFirstOption #auto="matAutocomplete">
<mat-option *ngFor="let county of counties" [value]="county.countyId">
{{county.name}}
</mat-option>
</mat-autocomplete>
<!-- <mat-select formControlName="countyId">
<mat-option *ngFor='let county of counties' [value]="county.countyId">
{{county.name}}
</mat-option>
</mat-select> -->
</mat-form-field>
这是我的ts 文件代码
ref: ComponentRef<any>;
newCustomerForm: FormGroup;
counties; // list of counties
subCounties;
filteredCounties: Observable<string[]>;
this.newCustomerForm = this._formBuilder.group({
nationalId: ['', Validators.required],
name: ['', Validators.required],
gender: ['', Validators.required],
phone1: [''],
phone2: [''],
countyId: ['', Validators.required],
subCountyId: ['', Validators.required],
bishopName: ['', Validators.required],
bishopPhone: ['', Validators.required],
address: ['', Validators.required],
additionalInfo: [''],
input1: [''],
input2: [''],
defaultingRecord: [''],
});
ngOnInit() {
// Getting the list of counties
this.countyService.getCounties().subscribe((response) => {
this.counties = response;
this.filteredCounties = this.newCustomerForm.valueChanges.pipe(
startWith(''),
map(value => this._filter(value))
);
});
// Getting a list of sub-counties
this.subCountyService.getSubCounties().subscribe((response) => {
this.subCounties = response;
});
}
private _filter(value: string): string[] {
const filterValue = value.toLowerCase();
return this.counties.filter(county=> county.name.toLowerCase().indexOf(filterValue) === 0);
}
【问题讨论】:
-
如果发布的答案没有帮助,请提供一个 stackblitz 演示
标签: javascript angular typescript