2021/08/09

Dynamic Form Field In Angular

Angular 的 form builder 蠻強大的,two way binding data 以及 validator 相當好用,其中有一個特性 FormArray 可以做許多運用,來做一個動態產生表單欄位的範例。

ts
import { Component, OnInit } from '@angular/core';
import { FormArray, FormBuilder, FormGroup } from '@angular/forms';

@Component({
  selector: 'app-dy-demo',
  templateUrl: './dy-demo.component.html',
  styleUrls: ['./dy-demo.component.scss']
})
export class DyDemoComponent implements OnInit {
  public form = this.fb.group({
    username: 'chan',
    family: this.fb.array([])
  })

  constructor(
    private fb: FormBuilder
  ) { }

  ngOnInit(): void {
  }

  public newLine(): FormGroup {
    return this.fb.group({
      name: '',
      age: ''
    })
  }

  public family(): FormArray {
    return this.form.get('family') as FormArray;
  }

  public add(): void {
    return this.family().push(this.newLine());
  }

  public remove(i: number): void {
    this.family().removeAt(i);
  }
}
html
<h3>{{ form.value | json }}</h3>
<div>
  <button (click)="add()">add</button>
</div>
<form action="" [formGroup]="form">
  <div>
    <input type="text" formControlName="username">
  </div>
  <div formArrayName="family">
    <ng-container *ngFor="let f of family().controls; let i=index" [formGroupName]="i">
      <div>
        username: <input type="text" formControlName="name"> age: <input type="number" formControlName="age">
        <button (click)="remove(i)">remove</button>
      </div>
    </ng-container>
  </div>
</form>

目前覺得 Angular 的內容真是易學難精啊。

沒有留言: