我希望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);
}
图片以更好地理解
最佳答案
您应该在模板中使用对象而不是单个属性:
<mat-form-field appearance="outline" fxFlex="50" class="pr-4">
<input type="text" placeholder="select county" name="country" matInput [formControl]="country" [matAutocomplete]="auto">
<mat-autocomplete autoActiveFirstOption #auto="matAutocomplete" [displayWith]="displayFn">
<mat-option *ngFor="let countryof countries" [value]="country">
{{country.name}}
</mat-option>
</mat-autocomplete>
</mat-form-field>
并像我在这里一样添加您的组件函数displayFn():
displayFn(country?: Country): string | undefined {
return country? country.name : undefined;
}