Template-drive Forms (中文:樣板驅動表單),裡面有四個要素,搞懂他們就可以完勝囉!
<form #heroForm="ngForm">:樣板參考變數,連結到 ngFormsrc\app\app.module.ts
-----
import { FormsModule } from '@angular/forms';
@NgModule({
    imports: [
        FormsModule
    ],
})
export class AppModule { }
app.component.ts
-----
export class AppComponent {
    testValue = '測試';
}
app.component.html
-----
<form>
    <div class="form-group">
    <label for="name">Name</label>
    </div>
        <input type="text" class="form-control" id="name" name="name" required [(ngModel)]="testValue">
    {{testValue}}
</form>
顯示
移除 input element 的 name 屬性
app.component.html
-----
<form>
    <div class="form-group">
    <label for="name">Name</label>
    </div>
        <input type="text" class="form-control" id="name" required [(ngModel)]="testValue">
    {{testValue}}
</form>
顯示
在 form 標籤內部,input 雙向繫結 需要有 name attribute ,才會恢復 雙向繫結 的能力,從上述範例可以看到
app.component.ts
-----
export class AppComponent {
    testValue = '測試';
}
app\app.component.html
-----
<form (ngSubmit)="onSubmit(heroForm)" #heroForm="ngForm">
    <div class="form-group">
        <label for="name">Name</label>
    </div>
    <input type="text" class="form-control" id="name" name="name" required [(ngModel)]="testValue" #invalidValue="ngModel" #spy>
    {{heroForm.value | json}}
    <button type="submit">送出</button>
</form>
顯示
input 的 name 屬性的值為 'name' ,就是上面 object{"name":"測試"} 的 Key("name"),而 object 的 value 是現在 input 的值("測試")
(ngSubmit)="onSubmit(heroForm)",表單送出事件,就可以把 heroForm 給 ts 檔去使用
#tag="ngModel":樣板參考變數,連結到 ngModel
明日說明表單驗證就會提及囉!