Tìm kiếm trang web

javascript - Angular: thiết lập form phản ứng với các input lặp động


Tôi phải đặt xác thực biểu mẫu phản ứng cho một biểu mẫu nơi các trường nhập liệu được tạo bằng cách lặp dữ liệu:

trình tạo biểu mẫu của tôi sẽ trông như thế này :

constructor(private formBuilder: FormBuilder) { 
    this.userForm = this.formBuilder.group({
      'inputOne': ['', [Validators.required]],
      'inputOne': ['', [Validators.required]],
       ...
      'inputN': ['', [Validators.required]]
    });
  }

và mẫu của tôi sẽ trông như thế này :

<form [formGroup]="userForm">
  <div class="form-group" *ngFor="let item of items; let i=index;">
        <label for="lastName">{{item.name}}</label>
        <input class="form-control" name="lastName" id="lastName" type="text" [formControlName]="item.name">
      </div>
</form>

nơi các mục được tải động từ backend của tôi

Làm thế nào để điền các điều khiển một cách động trong các biểu mẫu phản ứng của Angular?

Câu trả lời #1

nghe có vẻ bạn muốn một mảng biểu mẫu ở đây, chứ không phải một nhóm...

  constructor(private formBuilder: FormBuilder) { 
    // build an empty form array
    this.userForm = this.formBuilder.array([]); 
  }

  // call this whenever you need to add an item to your array
  private addItem(item) {
    // build your control with whatever validators / value
    const fc = this.formBuilder.control(i.lastName, [Validators.required]);
    this.userForm.push(fc); // push the control to the form
  }

  // call this function whenever you need to reset your array
  private resetFormArray(items) {
    this.userForm.clear(); // clear the array
    items.forEach(i => this.addItem(i)); // add the items
  }

<form [formGroup]="userForm">
  <div class="form-group" *ngFor="let item of items; let i=index;">
    <label for="lastName">{{item.name}}</label>
    <input class="form-control" name="lastName" id="lastName" type="text" [formControlName]="i">
  </div>
</form>

chú ý bạn đang sử dụng chỉ số cho tên điều khiển biểu mẫu ở đây