Skip to content

Form#

Form#

Reactive Form Template-driven Form
建立表單模型 明確的在 component 建立 FromControl 隱含式,使用 directive 在 template中
資料模型 結構化、不可變 非結構化、可變
資料流 同步 非同步
表單驗證 函式 指令

Reactive Form#

  • 可擴展性
  • 可重用性
  • 可測試性
  • 相關 Directive
    • FormControlDirective
    • FormControlName
    • FormGroupDirective
    • FormGroupName
    • FormArrayName
  • 需要實體化值與狀態

    .ts

    productName = new FormControl('');
    

    .html

    <input type = "text" [formControl] = "productName">
    

  • 要建立FormGroup的實體 .ts

    constructor(public builder: FormBuilder) {}
    this.form = this.builder.group({ ........ });
    

    .html

    <form [formGroup] = "form">...
    

  • FormControl 存取值

    • setValue()
      • 適用單個FormControl更換新值
    • pathValue()
      • 可指定替換特定屬性的值
    • get(’key’).value
      • 取得指定的 key 的 FormControl 值
  • 引用 @angular/forms 的 ReactiveFormsModule

Template-Driven Form#

  • 簡單容易
  • 擴展能力低
  • 使用ngModel建立及管理FromControl賦予的表單元素
  • 只需要定義變數

    .ts

    productName: string = "";
    
    .html
    <input type = "text" [(ngModel)] = "productName">
    

  • 引用 @angular/forms 的 FormsModule

  • novalidate
    • 避免預設的UI
  • ngNativeValidate
    • 開啟預設的UI

ngModel追蹤輸入項目和驗證能力#

  • 點擊過了?
    • Y: ng-touched
    • N: ng-untouched
  • 變更了?
    • Y: ng-dirty
    • N: ng-pristine
  • 驗證通過了?
    • Y: ng-valid
    • N: ng-invalid
  • 使用 # 命名並指向
  • 需搭配[(ngModel)]

ngForm#

  • 聯繫到表單
  • FormGroup 最上層
  • @Output
    • ngSubmit: 按下 submit 按鈕時的事件
  • @Input
    • control: FormGroup 的實體
    • controls{[key: string]: AbstractControl} 控制項的對應

共用的基礎元件#

AbstractControl → 提供所有控制元件和某些共享的行為,像是
validate、FormControl、FormGroup、FormArray

  • FormControl
    • 管理單一輸入項(input、select)的值及輸入驗證狀態
  • FormGroup
    • 管理一組輸入項(FormControl、FormGroup、FormArray) 的值及輸入驗證狀態
  • FormArray
    • 管理輸入項陣列的值及輸入驗證狀態
  • FormBuilder
    • 用來建立 FormControl 的方法

表單驗證#

  1. 確認輸入正確
  2. 降低因輸入錯誤的網路往返
  3. 降低 server 不必要的負擔

哪些要驗證#

  1. 必要欄位
  2. 輸入值必須在特定範圍
  3. 輸入值必須符合格式
  4. 長度限制

HTML5基本驗證#

HTML Angular
required ⭕
minlength、maxlength ⭕
pattern ⭕
email ⭕
min、max ❌

errors: 驗證錯誤的訊息#

  • required: 若為空白則為 true
  • minlength、maxlength: 不符合則為 true
  • pattern: 使用 RegEx 驗算,不符合則為 true
  • email: 不符合則為 true

ngModelGroup#

  • 上層為ngForm
  • 可以用來檢驗一組相關資料

NG_VALIDATORS#

  • 自訂驗證的必須要註冊providers
  • multi 必須設定為 true
  • 在 @Directive 指定 providers 資訊
    @Directive({
        selector: '[name]',
        providers: [{
            provide: NG_VALIDATORS,
            useExisting: CheckExtNoDirective,
            multi: true 
        }]
    })