javascript - 自动完成不过滤列表项Angular
问题描述
我希望该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;
}
推荐阅读
- jquery - 使用 ajax 调用在点击页面时触发事件
- php - Ajax:无法读取未定义的属性“类型”
- r - 从光栅文件获取坐标时避免圆形
- javascript - 使用车把助手生成新数组,并在 html 中使用新数组
- python - 浏览器加载时无响应窗口+文本未更改
- pyspark - 如何使用 pyspark 从 aws 胶水的时间戳中提取年份
- google-chrome - Selenium / Watir TCP 连接仅在 worker dyno heroku 上失败
- algorithm - 在连续数据中查找全局最小值
- php - Laravel 使用 Google Analytics - 使用未定义的常量
- java - 带有规范的 Spring 数据 jpa 限制结果