我无法从来自API的JSON响应对象填充下拉列表。.
component.ts代码
for (let k in keys) {
this.form.controls['id'].setValue(data[k].name);
console.log(data[k].name);
}
});
component.html代码
<mat-form-field>
<mat-label>Select a User</mat-label>
<mat-select formControlName="id">
<mat-option *ngFor="let opt of options" [value]="opt.data" >
{{ opt.data.name}}
</mat-option>
</mat-select>
</mat-form-field>
console.log(data)
0: {id: 1, name: "User1"}
1: {id: 2, name: "User2"}
2: {id: 3, name: "User3"}
3: {id: 4, name: "User4"}
...
console.log(data [k] .name); //这是我在下拉菜单中需要的数据
User1
User2
User3
User4
...
console.log数据显示每个对象的索引。我的JSON对象非常简单。
看起来像:
[
{
"id": 1,
"name": "User1"
},
{
"id": 2,
"name": "User2"
},...
]
请让我知道我在做什么错。谢谢。
编辑
来了
Stackblitz Example
答案 0 :(得分:2)
如果我正确理解了该问题,则您的API响应是一个列表,因此只需使用for循环将其绑定到Mat-Option
。
HTML代码:
<mat-card>
<form [formGroup]="form" (submit)="add()">
<mat-form-field>
<mat-label>Select a User</mat-label>
<mat-select formControlName="id">
\/\/
<mat-option *ngFor="let key of users" [value]="key">
{{ key.name }}
</mat-option>
</mat-select>
</mat-form-field>
<br/>
<div fxLayout>
<div>
<button
mat-raised-button
color="accent" [disabled] = "form.invalid">Save
</button>
</div>
</div>
</form>
</mat-card>
TS代码:
getUsers(): void {
this.usersService.getUsers().subscribe(users => {
this.users = users;
console.log(this.users)
});
}
答案 1 :(得分:0)
尝试一下:
<mat-form-field>
<mat-label>Select a User</mat-label>
<mat-select formControlName="id">
<mat-option *ngFor="let item of list" [value]="item" >
{{ item.name }}
</mat-option>
</mat-select>
</mat-form-field>
根据此修改TS文件:
list:any=[];
getUsers(): void {
this.usersService.getUsers()
.subscribe(users => {
this.users = users;
const data: User[] = this.users;
console.log('data',data)
console.log("object",Object.keys(data));
const keys: number[] = Object.keys(data) as any;
console.log("keys",keys);
console.log("users",this.users);
for (let k in keys) {
this.form.controls['id'].setValue(data[k].name);
console.log(data[k]);
this.list.push(data[k]);
}
});
}