angular ตัวอย่างการทำ dynamic form

เรามาดูตัวอย่างโค้ดการทำ dynamic form ใน angular กันครับ

ในตัวอย่างเราจะใช้ FormArray เพื่อทำ dynamic form

FormArray จะสามารถทำเป็น multiple FormControl หรือ FormGroup ได้ ดังนั้น เราจึงสามารถเพิ่มหรือลบ FormControl หรือ FormGroup ใน FormArray ได้

ตัวอย่างโค้ด

  1. import module มาก่อน
import { FormBuilder, FormArray, FormGroup, FormControl } from '@angular/forms';
  1. สร้าง properties ต่าง ๆ ขึ้นมาก่อน
export class MyComponent {
  myForm: FormGroup;

  constructor(private fb: FormBuilder) {
    this.myForm = this.fb.group({
      name: ['', Validators.required],
      addresses: this.fb.array([this.createAddress()])
    });
  }

  createAddress(): FormGroup {
    return this.fb.group({
      street: ['', Validators.required],
      city: ['', Validators.required],
      state: ['', Validators.required],
      zip: ['', Validators.required]
    });
  }

}
  1. ใน template เราจะสร้าง form group แต่ละอันใน formArray
<form [formGroup]="myForm">
  <label>Name:</label>
  <input formControlName="name" type="text">

  <div formArrayName="addresses">
    <div *ngFor="let address of myForm.get('addresses').controls; let i = index">
      <div [formGroupName]="i">
        <label>Street:</label>
        <input formControlName="street" type="text">

        <label>City:</label>
        <input formControlName="city" type="text">

        <label>State:</label>
        <input formControlName="state" type="text">

        <label>Zip:</label>
        <input formControlName="zip" type="text">

        <button (click)="removeAddress(i)">Remove</button>
      </div>
    </div>
  </div>

  <button (click)="addAddress()">Add Address</button>
</form>
  1. ใน component class เราก็สร้าง method add และ remove ไว้
export class MyComponent {
  ...

  addAddress() {
    this.addresses.push(this.createAddress());
  }

  removeAddress(index: number) {
    this.addresses.removeAt(index);
  }

  get addresses(): FormArray {
    return this.myForm.get('addresses') as FormArray;
  }
}


Copyright © 2023 Devcode Code Example - Powered by www.doesystem.com