響應式表單

比較接近 Vue 的 vee-validate 或 Composition API 的寫法

1. 設置響應式表單模組

首先,需要引入必要的模組:

import { ReactiveFormsModule, FormControl, FormGroup } from '@angular/forms';

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [ReactiveFormsModule],  // 引入響應式表單模組
  template: `
    <form>
      <label>Name
        <input type="text" />
      </label>
      <label>Email
        <input type="email" />
      </label>
      <button type="submit">Submit</button>
    </form>
  `
})

2. 創建表單控制對象

在組件類中定義表單結構:

export class AppComponent {
  // 創建一個 FormGroup 實例
  profileForm = new FormGroup({
    // 為每個表單字段創建 FormControl
    name: new FormControl(''),    // 空字串作為初始值
    email: new FormControl('')
  });
}

3. 連接表單控制器

在模板中綁定表單控制器:

@Component({
  template: `
    <form [formGroup]="profileForm">
      <label>
        Name
        <input type="text" formControlName="name" />
      </label>
      <label>
        Email
        <input type="email" formControlName="email" />
      </label>
      <button type="submit">Submit</button>
    </form>
  `
})

4. 顯示表單數據

可以直接在模板中訪問表單值:

@Component({
  template: `
    <h2>Profile Form</h2>
    <form [formGroup]="profileForm">
      <!-- 表單控件 -->
    </form>
    
    <!-- 顯示表單數據 -->
    <p>Name: {{ profileForm.value.name }}</p>
    <p>Email: {{ profileForm.value.email }}</p>
  `
})

5. 處理表單提交

在組件類中添加提交處理方法:

export class AppComponent {
  profileForm = new FormGroup({
    name: new FormControl(''),
    email: new FormControl('')
  });

  // 處理表單提交
  handleSubmit() {
    alert(
      this.profileForm.value.name + ' | ' + this.profileForm.value.email
    );
  }
}

6. 綁定提交事件

使用 ngSubmit 事件處理表單提交:

@Component({
  template: `
    <form 
      [formGroup]="profileForm" 
      (ngSubmit)="handleSubmit()"
    >
      <!-- 表單控件 -->
    </form>
  `
})

重要概念說明

  1. FormGroup

    • 表單的容器

    • 包含多個 FormControl

    • 可以一次性訪問所有表單值

  2. FormControl

    • 單個表單控件

    • 可以設置初始值

    • 跟踪值的變化和驗證狀態

  3. formControlName

    • 將模板中的輸入框與 FormControl 連接的指令

    • 必須與 FormGroup 中定義的鍵名匹配

  4. [formGroup]

    • 將整個表單與 FormGroup 實例綁定

    • 啟用表單的響應式特性

  5. (ngSubmit)

    • 表單提交事件

    • 優於普通的 submit 事件

    • 自動防止表單的默認提交行為

與模板驅動表單的比較

響應式表單:

// 響應式表單
profileForm = new FormGroup({
  name: new FormControl('')
});

<form [formGroup]="profileForm">
  <input formControlName="name">
</form>

模板驅動表單:

// 模板驅動表單
user = { name: '' };

<form>
  <input [(ngModel)]="user.name" name="name">
</form>

主要區別:

  • 響應式表單在組件類中定義結構

  • 模板驅動表單在模板中定義結構

  • 響應式表單提供更強的類型安全性

  • 響應式表單更適合複雜的表單邏輯

Last updated