我在填充来自API的JSON Response对象的下拉列表时遇到了麻烦。
for (let k in keys) {
this.form.controls['id'].setValue(data[k].name);
console.log(data[k].name);
}
});
<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>
0: {id: 1, name: "User1"}
1: {id: 2, name: "User2"}
2: {id: 3, name: "User3"}
3: {id: 4, name: "User4"}
...
User1
User2
User3
User4
...
console.log数据显示每个对象的索引。我的JSON对象非常简单。 看起来像:
[
{
"id": 1,
"name": "User1"
},
{
"id": 2,
"name": "User2"
},...
]
请让我知道我做错了什么。谢谢。
编辑 这是工作Stackblitz Example
如果我正确理解了这个问题,那么您的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)
});
}
试试这个:
<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]);
}
});
}