iT邦幫忙

2019 iT 邦幫忙鐵人賽

DAY 17
0
Modern Web

Angular初期筆記系列 第 17

DAY17-Angular6之表單-Template-drive Forms 驗證

前情提要

ts
-----
testValue = '';
html
-----
[( ngModel )] = "testValue"

[( ngModel )] 是一個語法糖,屬性繫結和事件繫結兩者的結合,它需要搭配一個在ts已宣告過的變數綁定,也就是說,不管哪種繫結所得到的都是變數的值

html
-----
#invalidValue="ngModel"

#invalidValue 代表著參考到 ngModel 這個 directive,你就可以使用這個 directive 的 property

屬於 directive 的 ngModel 擁有的 property
https://angular.io/api/forms/NgModel

實作一個驗證

app/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" #invalidValue="ngModel">
    <div *ngIf="invalidValue.invalid">
        您尚未填寫資料
    </div>
</form>
app\app.component.ts
-----
export class AppComponent {
    testValue = '測試';
}

顯示
https://ithelp.ithome.com.tw/upload/images/20181027/20107754xN2Yv2owgj.png

刪除 input 文字
顯示
https://ithelp.ithome.com.tw/upload/images/20181027/20107754WXtdRSV4oD.png

*ngIf="invalidValue.invalid"

*ngIf

  • true 顯示 element; false 隱藏 element

invalidValue.invalid:

  • invalidValue 是 參考樣板變數的名稱
  • invalid 指「是否未驗證的屬性」,true 未驗證;false 驗證成功

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

尚未有邦友留言

立即登入留言