Angular6中的嵌套Formarrays

时间:2018-09-05 15:35:14

标签: angular

我正在尝试在formarray中插入formarray以使其正常工作。但是我看不到做对了。想法是使以下内容以某种形式工作:

项目[0]:    Sku:“字符串”,    收到:“字符串”,    数量:“字符串”,    跟踪[0]:“字符串”,    Tracking [1]:“字符串”

项目[1]:    Sku:“字符串”,    收到:“字符串”,    数量:“字符串”,    Tracking [0]:“字符串”

每个项目都应该有一个称为“跟踪”的嵌套数组。我想在每个项目数组旁边添加一个按钮,以添加跟踪。

这是我到目前为止所拥有的:

create-return.component.ts

import { Component, OnInit } from '@angular/core';
import { MatFormField, MatSelect, MatToolbar } from '@angular/material';

import {
  FormControl,
  FormGroup,
  FormBuilder,
  FormArray,
  Validators
} from '@angular/forms';
import { ReturnsService } from '../../returns.service';

@Component({
  selector: 'app-create-return',
  templateUrl: './create-return.component.html',
  styleUrls: ['./create-return.component.css']
})
export class CreateReturnComponent implements OnInit {
  inputData: FormGroup;

  constructor(private returns: ReturnsService, private fb: FormBuilder) {
    // this.inputData = new FormGroup({
    //   items: new FormGroup({
    //     sku: new FormControl(),
    //     quantity: new FormControl(),
    //     received: new FormControl()
    //   }),
    //   orderId: new FormControl(),
    //   isPrime: new FormControl(),
    //   note: new FormControl(),
    //   reason: new FormControl()
    // });
  }

  ngOnInit() {
    this.inputData = this.fb.group({
      items: this.fb.array([], Validators.required),
      // trackings: this.fb.array([], Validators.required),
      orderId: ['', Validators.required],
      isPrime: ['', Validators.required],
      // note: '',
      reason: ''
    });

    this.addItemToForm();
    this.addTrackingsToForm();
    // console.log(this.inputData);
    console.log(this.itemsForm.controls[0]);
  }

  get itemsForm() {
    return this.inputData.get('items') as FormArray;
  }

  get trackingsForm() {
    let track = this.itemsForm as FormArray;
    // return this.itemsForm.get('sku') as FormArray;
    return track;
  }

  addItemToForm() {
    const items = this.fb.group({
      sku: ['', Validators.required],
      quantity: ['', Validators.required],
      received: ['', Validators.required],
      trackings: this.fb.array([])
    });

    this.itemsForm.push(items);
  }

  addTrackingsToForm() {
    const tracking = this.fb.group({
      trackings: ['', Validators.required]
    });

    this.trackingsForm.controls[0]['controls']['trackings'].push(tracking);
  }

  deleteItemFromForm(i) {
    this.itemsForm.removeAt(i);
  }

  deleteTrackingFromForm(i) {
    this.trackingsForm.removeAt(i);
  }

  submitData() {
    console.log(this.inputData.value);
    // this.returns.createReturn(this.inputData.value).subscribe(data => {
    //   this.returns.openSnackBar('Return Created!', '');
    //   this.inputData.reset();
    // });
  }
}

create-return.component.html

<!-- Items[ { sku->string,quantity->number,received->number } ], orderId->, isPrime->true|false, note->string, reason->string-->

<form [formGroup]="inputData" class="center-width-separator" style="margin-top: 2%;">
  <mat-card>
    <mat-toolbar class="center-width-separator mat-header-create">
      <span>Create Return</span>
    </mat-toolbar>
    <mat-card-title>Order</mat-card-title>
    <mat-form-field class="input-separator">
      <input matInput placeholder="Order ID" formControlName="orderId">
    </mat-form-field>
    <mat-form-field>
      <mat-select formControlName="isPrime" placeholder="Prime?">
        <mat-option value="true">Yes</mat-option>
        <mat-option value="false">No</mat-option>
      </mat-select>
    </mat-form-field>
    <button mat-stroked-button (click)="addItemToForm()" style="margin: 0 5px;">Add Item</button>


    <div formArrayName="items">
      <mat-card-title style="padding-top: 10px;">Items</mat-card-title>
      <div *ngFor="let items of itemsForm.controls; let i=index" [formGroupName]="i">
        <!-- SKU -->
        <mat-form-field class="input-separator">
          <input matInput placeholder="Sku" formControlName="sku">
        </mat-form-field>
        <!-- Quantity -->
        <mat-form-field class="input-separator">
          <input matInput placeholder="Quantity" formControlName="quantity">
        </mat-form-field>
        <!-- Received -->
        <mat-form-field class="input-separator">
          <input matInput placeholder="Received" formControlName="received">
        </mat-form-field>
        <button mat-stroked-button (click)="addItemToForm()" style="margin: 0 5px;">Add Item</button>
        <button mat-raised-button color="warn" (click)="deleteItemFromForm(i)" style="margin: 0 2%;">Delete Item</button>

        <p></p>
        <div formArrayName="trackings">
          <mat-card-title style="padding-top: 10px;">Trackings</mat-card-title>
          <div *ngFor="let trackings of trackingsForm.controls; let o=index" [formGroupName]="o">
            <mat-form-field class="input-separator">
              <input matInput placeholder="Tracking Number" formControlName="trackings">
            </mat-form-field>
            <!-- <button mat-stroked-button (click)="addTrackingsToForm(i)" style="margin: 0 5px;">Add Item</button> -->

            <!-- <button mat-raised-button color="warn" (click)="deleteTrackingFromForm(i)" style="margin: 0 2%;">Delete Item</button> -->
          </div>
        </div>
      </div>
    </div>

    <mat-divider></mat-divider>


    <p></p>
    <!-- <mat-form-field class="input-separator" style="width: 80%;">
      <textarea matInput rows="5" placeholder="Notes" formControlName="note"></textarea>
    </mat-form-field> -->
    <p></p>

    <!-- <mat-form-field class="input-separator" style="width: 80%;">
      <textarea matInput rows="5" placeholder="Reason for return" formControlName="reason"></textarea>
    </mat-form-field> -->
    <p></p>
    <p></p>
    <button mat-raised-button color="primary" [disabled]="inputData.invalid" (click)="submitData()">Submit</button>
  </mat-card>
  <p></p>
</form>

任何帮助将不胜感激。谢谢

编辑:问题:

每当我添加“项目”组时,都会将跟踪字段添加到该字段。我需要的是每个Items字段都有各自的跟踪字段。有时它们的值为零,有时为3或更多。

0 个答案:

没有答案