iT邦幫忙

2019 iT 邦幫忙鐵人賽

DAY 18
0
Modern Web

Angular初期筆記系列 第 18

DAY18-Angular6之表單-簡易Reactive Form

前言

昨日上了 Kevin 大大的 Reactive Form ,發現假如有需要動態驗證、動態產生表單和比較複雜類型的表單狀況,使用 Reactive Form 處理應當會比 Template-Drive Form 好解決,上課途中也發現自己 JS 對於物件處理不夠熟練還有 RxJS ,一坑還有一坑坑,本文只會實作一個簡單的表單,進階的處理還在消化中。

匯入 ReactiveFormModule

app.module.ts
-----
import { ReactiveFormComponent } from './reactive-form/reactive-form.component';

@NgModule({
    imports: [ReactiveFormsModule]
})

export class AppModule { }

先備知識

FormControl
追蹤 值 和 驗證狀態在個別的 form control
https://angular.io/api/forms/FormControl

FormGroup
追蹤 值 和 驗證狀態在 一群 FormControl 實體
https://angular.io/api/forms/FormGroup

實作

component.ts
-----
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl } from '@angular/forms';

@Component({
selector: 'app-reactive-form',
templateUrl: './reactive-form.component.html',
styleUrls: ['./reactive-form.component.css']
})

export class ReactiveFormComponent implements OnInit {
    formData = new FormGroup({
        name : new FormControl(''),
        phone : new FormControl(''),
        checkSomething : new FormControl('true')
    });

    constructor() { }

    ngOnInit() {
    }
}
component.html
-----
<div class="container">
    <form [formGroup]="formData">
        <div class="form-group">
            <input type="text" class="form-control" id="name" formControlName="name">
        </div>
        <div class="form-group">
            <input type="text" class="form-control" id="phone" formControlName="phone">
        </div>
        <div class="form-group form-check">
            <input type="checkbox" class="form-check-input" id="exampleCheck1" formControlName="checkSomething">
        <label class="form-check-label" for="exampleCheck1">Check me out</label>
        </div>
        <button type="submit" class="btn btn-primary">送出</button>
    </form>
    {{formData.value|json}}
</div>

在實作官網練習讓我困擾一陣子的東西就是:formControlName 、 [formControl]
原本的 [formControl] 為什麼在 [formGroup] 加入後就沒用了!而要改為 formControlName
其實就變數方面來看,在 component.ts 宣告的變數其實只有 formData ;name、phone 和 checkSomething 都是包含在 formData 內,屬性繫結要綁定是綁定變數,既然明擺著沒有又怎麼綁定的到呢!

[formControl]="formData.get('name')" 但改成這樣就可以囉!但或許是寫這樣太麻煩 Angular 才取而代之用了 formControlName="name" 這樣輕鬆又方便是吧!

form group 包含群組 控制項,使用 FormGroup directive 綁定到表單元素,建立一種在 model 和 包含 input 表單之間 的 通訊層,formControlName 輸入框架 從 FormControlName directive 綁定到個別輸入框定義在FormGroup 的 form control。
form controls 在各自的 elements 中互相流通,他們也可以改變 form group 實體,從 model value 提供數據的來源
https://angular.io/guide/reactive-forms#step-2-associating-the-formgroup-model-and-view

顯示
https://ithelp.ithome.com.tw/upload/images/20181028/20107754XchPA8GP64.png


上一篇
DAY17-Angular6之表單-Template-drive Forms 驗證
下一篇
DAY19-Angular6之實現父到子傳值
系列文
Angular初期筆記30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言