【发布时间】:2018-04-11 21:45:05
【问题描述】:
我有这个例子Demo
我试图在 City 中显示 Florida,但对我来说不起作用,我只能显示 3,city_id。为此,我使用了以下代码:
我有 2 个班级,客户和城市
city: City[] = [
{
name: 'Arkansas',
city_id: '1'
},
{
name: 'California',
city_id: '2'
},
{
name: 'Florida',
city_id: '3'
},
{
name: 'Texas',
city_id: '4'
}
];
client: Client[] = [
{
client_name: 'MyName',
city_id: '3',
email: 'myemail@gmail.com'
}
];
我试图用这个函数在 html 中显示这个值:
populateForm() {
this.myform.patchValue({
city_id: this.client.map(x => x.city_id),
email: this.client.map(x => x.email),
client_name: this.client.map(x => x.client_name)
})
}
email和client_name可以html显示,但是city_id没有。
我的html代码:
<form [formGroup]="myform">
<input formControlName="client_name" placeholder="name">
<input formControlName="email" placeholder="email" >
<input formControlName="city_id" Input placeholder="City" aria-label="State" [matAutocomplete]="auto" [formControl]="cityy">
<mat-autocomplete #auto="matAutocomplete">
<mat-option *ngFor="let item of filteredOptionsCity | async" [value]="item.name">
<span>{{ item.name }}</span>
</mat-option>
</mat-autocomplete>
</form>
我的结果:
我要显示:
**`
client_name:MyName city_id:佛罗里达州电子邮件:myemail@gmail.com
`**
我在等待你的建议。
谢谢 编辑:
client: Client;
populateForm() {
this.activatedRoute.params.subscribe(
params => {
this.ws.getClientById(params['id']).subscribe(
client => {
this.client = client;
this.patchForm();
}
);
}
);
}
patchForm() {
this.myform.controls['client_name'].setValue(this.client.clientName);
this.editClientForm.controls['city_id'].setValue(this.client.city);
this.editClientForm.controls['email'].setValue(this.client.email);
}
类:
export class Client {
clientName: string;
email: string;
city: City[];}
export class City {
city_id: string;
name: string;}
城市
cityes: City[] = [];
selectedCity: string;
ngOnInit() {
this.ws.getAllCity().subscribe(
cityes => {
this.cityes = cityes.map((city) => {
return new City(city);
});
console.log(cityes) //return all my city
}
);
this.selectedCity = this.cityes.filter(
x => x.city_id === this.client.city
.map(x => x.city_id)[0])
.map(y => y.name).join('')
console.log(this.cityes) //cityes is empty
}
更新
patchForm() {
this.myform.controls['client_name'].setValue(this.client.clientName);
this.editClientForm.controls['email'].setValue(this.client.email);
this.editClientForm.controls['city_id'].setValue(this.selectedCity = this.cityes.filter(
x => x.city_id === this.client.city
.map(x => x.city_id)[0])
.map(y => y.name).join(''))
}
}
【问题讨论】:
-
这是因为您在客户端数组中有
city_id: '3',,您正在修补到formcontrol -
你能尝试一下如何解决这个问题吗?
-
在自动完成输入任何内容之前,您想默认显示城市名称吗?
-
是的,我想默认显示城市名称。在这个经验中。佛罗里达
-
请问可以吗?
标签: angular typescript autocomplete angular-material angular-material2