我为自己的项目使用自动填充材料,但我不了解如何使用[displayWith]。我尝试了一些示例,但没有在html中显示名称,只有id。
我的HTML代码:
<form [formGroup]="editClientForm">
<input formControlName="city_id" id="city_id" matInput placeholder="Select City*" aria-label="State" [matAutocomplete]="auto1"
autoActiveFirstOption [formControl]="city">
<mat-autocomplete #auto1="matAutocomplete" [displayWith]="displayFnCity">
<mat-option (onSelectionChange)="updateForm($event, city.city_id, 'city_id')" *ngFor="let city of filteredOptionsCity | async"
[value]="city.name">
{{ city.name }}
</mat-option>
</mat-autocomplete>
</form>
我的ts组件:
cityid = 0;
filteredOptionsCity: any;
city: FormControl = new FormControl();
editClientForm: FormGroup;
this.editClientForm = this.fb.group({
'city_id': new FormControl('', Validators.required),
});
ngOnInit() {
this.filteredOptionsCity = this.city.valueChanges.pipe(
startWith(''),
map(value => this.filterCity(value))
);
}
populateForm() {
this.activatedRoute.params.subscribe(
params => {
this.clientService.getClientById(params['id']).subscribe(
client => {
this.client = client;
console.log(client)
this.editClientForm.controls['city_id'].setValue(client.city);
console.log(client.city);
}
);
}
);
}
// City
filterCity(val: string): City[] {
if (val) {
let filterValue = val.toLowerCase();
console.log(this.cityes)
return this.cityes.filter(city => city.name.toLowerCase().startsWith(filterValue));
}
return this.cityes;
}
updateForm(ev: any, idd: any, componentid: any) {
if (ev.isUserInput) {
if (componentid === 'city_id') {
this.cityid = idd;
this.editClientForm['controls']['city_id'].setValue(ev.source.value);
} else {
console.log('test');
}
}
}
我的班级客户:
export class Client {
city: City[];}
我的班级城市:
export class City {
city_id: string;
name: string; }
在html中显示clity_id,我想要城市名称。
我尝试使用此代码,但没有任何事情发生:
getName(productid: string) {
const [filteredProdG] = this.cityes.filter(pt => pt.city_id === productid);
if (typeof filteredProdG !== 'undefined' && productid === filteredProdG.city_id) {
return filteredProdG.name;
}
}
1. displayFnCity(city?: City): string {
console.log(city ? city.name : undefined) //show undefined
return city ? city.name : undefined;
}
2. displayFnCity(city) {
console.log(city.name) //show undefined
return city.name;
}
3。如果我在html中尝试[displayWith]="displayFn"
或[displayWith]="displayFnCity"
只显示id_city
请知道如何解决这个问题?
答案 0 :(得分:0)
[displayWith]
函数将传递给[value]
对象。由于您使用的是[value]="city.name"
,因此您无需使用[displayWith]
,因为默认情况下,自动填充功能会显示[value]
。通常,当[displayWith]
绑定到不是人类可识别字符串的对象时,会使用[value]
。例如,如果您使用[value]="city"
,那么您还需要使用[displayWith]="displayFnCity"
(您的#1)。