我想创建一个带有角度(17)和角度材料的自动完成输入。我有一个数组 ob 对象(位置),它有一个 id、坐标和可选的地址。我已经可以过滤值并将它们显示在表单输入中,但我无法管理它只保存表单控件上的地址。我只能存储整个对象,但我只想保存 id。这可能吗?
模板:
<form [formGroup]="form">
<mat-form-field>
<input
matInput
placeholder="Search"
[matAutocomplete]="auto"
[formControlName]="'location'" />
<mat-autocomplete
#auto="matAutocomplete"
[displayWith]="displayFn">
<mat-option
*ngFor="let option of filteredOptions | async"
[value]="option">
{{ displayFn(option) }}
</mat-option>
</mat-autocomplete>
</mat-form-field>
</form>
组件
locations: Location[] = [
{ id: '1', coordinates: { lat: 10, lon: 20 }, address: { street: 'Street 1', housenumber: '1', city: 'City 1' } },
{ id: '2', coordinates: { lat: 30, lon: 40 }, address: { street: 'Another Street 2', housenumber: '2', city: 'City 2' } },
{ id: '3', coordinates: { lat: 50, lon: 60 } }
];
form = this.createForm();
filteredOptions: Observable<Location[]> = of([]);
constructor(private _formBuilder: FormBuilder) {
this.filteredOptions = this.form.controls['location'].valueChanges.pipe(
startWith(''),
map((value) => (typeof value === 'string' ? value : value.id)),
map((id) => (id ? this._filter(id) : this.locations.slice()))
);
}
createForm(): FormGroup {
return this._formBuilder.nonNullable.group({
location: new FormControl<string>('')
})
}
displayFn(location: Location): string {
if(location) {
if(location.address) {
return location.address.street + ' ' + location.address.housenumber + ', ' + location.address.city
} else {
return location.coordinates.lat + ', ' + location.coordinates.lon;
}
}
return '';
}
private _filter(value: string): any[] {
const filterValue = value.toLowerCase();
return this.locations.filter(
(option) => {
return option.id.toString().toLowerCase().includes(filterValue) ||
(option.address &&
(option.address.street.toLowerCase().includes(filterValue) ||
option.address.city.toLowerCase().includes(filterValue))) ||
option.coordinates.lat.toString().toLowerCase().includes(filterValue) ||
option.coordinates.lon.toString().toLowerCase().includes(filterValue)
}
);
}
您需要使用
[value]="option.id"
。
这样当选择一个选项时,表单控件中只会存储Location对象的id。