【问题标题】:How to get a desired output as custom array of objects?如何获得所需的输出作为自定义对象数组?
【发布时间】:2021-07-15 09:50:29
【问题描述】:

您好,我正在研究 Angular 8,所以在这里我遇到了一个问题,我有这样的简单 api 数据:

this.inputData = [
      {
        id: 1,
        name: "john"
      },
      {
        id: 2,
        name: "joe"
      },
      {
        id: 3,
        name: "juke"
      }
    ];

所以对于每个学生,我想给和发送权重并将数据发送到另一个 api,所以我的示例预期结果应该是

 [{
     nameID: 1,weight:22
     },
     {
     nameID: 2,weight:22
     }
     {
     nameID: 3,weight:22
     }
     ]

这里是示例stackblitz

【问题讨论】:

  • 您不能使用 ngFor 循环创建 标签,因为您必须分别处理每个输入标签。

标签: angular angular7 angular8 angular9 angular10


【解决方案1】:

https://stackblitz.com/edit/angular-ivy-ayczfn?file=src%2Fapp%2Fapp.component.html

app.component.ts

import { Component, VERSION } from "@angular/core";

@Component({
  selector: "my-app",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent {
  name = "Angular " + VERSION.major;
  inputData: any = [];
  weightperson: any;
  outputdata: any = [];

  constructor() {
    this.getApiData();
  }

  getApiData() {
    this.inputData = [
      {
        id: 1,
        name: "john"
      },
      {
        id: 2,
        name: "joe",
        weight: 44
      },
      {
        id: 3,
        name: "juke"
      }
    ];
  }

  getOutput() {
    this.outputdata = this.inputData.map(x => {
      return {
        nameID: x.id,
        weight: x.weight
      };
    });
    // expectedOutput is
    // [{
    // nameID: 1,weight:22
    // },
    // {
    // nameID: 2,weight:22
    // }
    // {
    // nameID: 3,weight:22
    // }
    // ]
  }
}

app.component.html

  <div class="container pt-5 pb-5">
  <div class="row pt-5">
    <table class="table table-striped table-bordered">
      <thead>
        <tr>
          <th scope="col">name</th>
          <th scope="col">Weights</th>
        </tr>
      </thead>
      <tbody>
        <tr *ngFor="let row of inputData; let i = index">
          <td>{{ row.name }}</td>
          <td>
            <input type="text" name="weightperson" class="form-control" [(ngModel)]="row.weight">
          </td>
        </tr>
        <button (click)="getOutput()">Submit</button>
      </tbody>
    </table>
  </div>
</div>
{{outputdata | json}}

礼貌:Sujendra Shrestha (sujen.2009@gmail.com)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-10-16
    • 1970-01-01
    • 1970-01-01
    • 2017-02-01
    • 2021-01-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多