面对将数据从JSON对象绑定到的问题

问题描述 投票:0回答:2

我在填充来自API的JSON Response对象的下拉列表时遇到了麻烦。

  1. component.ts代码 for (let k in keys) { this.form.controls['id'].setValue(data[k].name); console.log(data[k].name); } });
  2. 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>
  3. 的console.log(数据) 0: {id: 1, name: "User1"} 1: {id: 2, name: "User2"} 2: {id: 3, name: "User3"} 3: {id: 4, name: "User4"} ...
  4. 的console.log(数据[K]。名称); //这是下拉列表中我需要的数据 User1 User2 User3 User4 ...

console.log数据显示每个对象的索引。我的JSON对象非常简单。 看起来像:

[
 {
    "id": 1,
    "name": "User1"
 },
 {
    "id": 2,
    "name": "User2"
 },...
]

请让我知道我做错了什么。谢谢。

编辑 这是工作Stackblitz Example

json angular angular-material associative-array angular7
2个回答
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)
  });
}

Forked_Stackblitz


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]);
            }
        });
    }
© www.soinside.com 2019 - 2024. All rights reserved.