以反射形式显示和输入行中的值Angular 4

时间:2017-11-06 11:34:05

标签: angular angular-reactive-forms angular4-forms reactive-forms

" this.orders"是以下API的结果。我的问题是如何获取material_purchase_orders下的material.name并仅编辑其数量。你的解决方案是对的。我无法获得此material.name及其编辑数量。

  

TS

 this.route.paramMap
   .switchMap((params: ParamMap) => 
      this.purchaseOrderService.getOrder(+params.get('id')))
        .subscribe(
          (order:any) => {
            this.orders = order;
            console.log(order);
            this.loading = false;
         },
         error => {
            console.log(error);
            this.loading = false;
          }) 

      };




this.myForm = this.fb.group({
      rows: this.fb.array([])
  })

initGroup() {
    let rows = this.myForm.get('rows') as FormArray;
    rows.push(this.fb.group({
      prod_id: [null, Validators.required],
      quantity: [null, Validators.required],
    }))
  }
  

JSON

{
  "id": 11,
  "reference": "pek567",
  "supplier_id": 1,
  "user_id": 1,
  "project_id": 5,
  "total": 100,
  "transaction_date": "2017-10-08",
  "created_at": "2017-10-31 13:10:44",
  "updated_at": "2017-10-31 13:10:44",
  "user": {
    "id": 1,
    "name": "John",
    "email": "john@gmail.com",
    "created_at": "2017-10-26 07:32:53",
    "updated_at": "2017-10-26 11:58:44"
  },
  "supplier": {
    "id": 1,
    "name": "Not Available",
    "address": "Not Available",
    "city": "Not Available",
    "contact_number": "Not Available",
    "created_at": "2017-10-26 16:12:22",
    "updated_at": "2017-10-26 16:12:22"
  },
  "material_purchase_orders": [
    {
      "id": 11,
      "material_id": 49,
      "purchase_order_id": 11,
      "quantity": 1,
      "unit": "pcs",
      "price": 100,
      "created_at": "2017-10-31 13:10:44",
      "updated_at": "2017-10-31 13:10:44",
      "material": {
        "id": 49,
        "sku": "D16789",
        "name": "Door",
        "created_at": "2017-10-26 03:33:06",
        "updated_at": "2017-10-26 03:33:06"
      }
    }
  ],
  "user_name": "John"
}

1 个答案:

答案 0 :(得分:0)

由于您的数据如下所示:

obj = {material_purchase_orders: [{material: {id: 1, name: 'material1'}, quantity:2}, ..]}

// call this when you have your data
this.patchValues();

// this is where you store your data from api
productsFromApi = [];

patchValues() {
  let rows = this.myForm.get('rows') as FormArray;
  this.obj.material_purchase_orders.forEach(material => {
    rows.push(this.fb.group({material_name: material.material.name, quantity: material.quantity}))
  })
}

然后,您只需从视图中删除products的迭代,而是显示formarray中的值:

<tbody>
  <tr *ngFor="let row of myForm.controls.rows.controls; let i = index" [formGroupName]="i">
    <td>{{row.value.material_name}}</td>
    <td><input type="number" class="col-md-6" formControlName="quantity"></td>
  </tr>
</tbody>

<强> DEMO