iT邦幫忙

2019 iT 邦幫忙鐵人賽

DAY 16
0
Modern Web

Angular初期筆記系列 第 16

DAY16-Angular6之表單-Template-drive Forms

基礎

Template-drive Forms (中文:樣板驅動表單),裡面有四個要素,搞懂他們就可以完勝囉!

  • form 裡面的 name
  • [(hello)]="":雙向繫結
  • <form #heroForm="ngForm">:樣板參考變數,連結到 ngForm
  • #tag="ngModel":樣板參考變數,連結到 ngModel

匯入 FormsModule

src\app\app.module.ts
-----
import { FormsModule } from '@angular/forms';

@NgModule({
    imports: [
        FormsModule
    ],
})
export class AppModule { }

Form 內的 name 屬性

注意和「雙向繫結」作用

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>

顯示
https://ithelp.ithome.com.tw/upload/images/20181026/20107754nRzccqW0Lx.png

移除 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>

顯示
https://ithelp.ithome.com.tw/upload/images/20181026/201077543ua455h7gv.png
在 form 標籤內部,input 雙向繫結 需要有 name attribute ,才會恢復 雙向繫結 的能力,從上述範例可以看到

注意和「ngForm」作用

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>

顯示
https://ithelp.ithome.com.tw/upload/images/20181026/20107754UQI8Xqi7oo.png

input 的 name 屬性的值為 'name' ,就是上面 object{"name":"測試"} 的 Key("name"),而 object 的 value 是現在 input 的值("測試")

(ngSubmit)="onSubmit(heroForm)",表單送出事件,就可以把 heroForm 給 ts 檔去使用

#tag="ngModel":樣板參考變數,連結到 ngModel
明日說明表單驗證就會提及囉!


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

尚未有邦友留言

立即登入留言