Angular 2 ngForm中的ngModel、[ngModel]和[(ngModel)]的寫法
“對呀對呀!……回字有四樣寫法,你知道么?”,當時魯大大如此諷刺孔乙己,意味著老孔這個被科舉制毒害的人注意此種無用之物實在可悲。但是在Angular 2的世界中,很少存在無用之物,ngModel有三種寫法,你知道嗎?
表單的設計永遠都是應用的重頭戲,而其中最基本的功能點即是通過一個個輸入組件實現(xiàn)的,為此Angular 2為我們提供了鋒利的武器:ngModel。而其不同的使用方式有著大不相同的作用:
ngModel
如果單獨使用ngModel,且沒有為其賦值的話,它會在其所在的ngForm.value對象上添加一個property,此property的key值為ngModel所在組件設置的name屬性的值:
<form novalidate #f="ngForm"> <input type='text' name='userName' placeholder='Input your userName' ngModel> </form> <p> {{ f.value | json }} // { "userName": "" } </p>
此時需要注意的是,單獨使用ngModel時,如果沒有為ngModel賦值的話,則必須存在name屬性。
也就是說,單獨ngModel的作用是通知ngForm.value,我要向你那里加入一個property,其key值是組件的name屬性值,其value為空字符串。
[ngModel]
可是,如果想向ngForm中添加一個有默認值的property需要怎么做呢?這時就需要使用單向數(shù)據(jù)綁定的格式了,也就是[ngModel]:
this.model = { userName: 'Casear' }; <form novalidate #f="ngForm"> <input type='text' name='userName' placeholder='Input your userName' [ngModel]='model.userName'> </form> <p> {{ f.value | json }} // { "userName": "Casear" } {{ model | json }} // { "userName": "Casear" },不會隨著f.value的變化而變化 </p>
這里我們使用了單向數(shù)據(jù)綁定的特點,可以為ngForm.value添加一個帶有初始值的property。
注意單向數(shù)據(jù)綁定的特點,此時在表單輸入框中做的任何改變都不會影響model中的數(shù)據(jù),也就是說this.model.userName不會隨著輸入框的改變而改變。不過輸入框改變會體現(xiàn)在f.value中。
[(ngModel)]
上述的單向數(shù)據(jù)綁定在單純地提供初始值很有用,不過總是有些場景需要將用戶輸入體現(xiàn)在我們的model上,此時就需要雙向數(shù)據(jù)綁定了,也即[(ngModel)]:
this.model = { userName: 'Casear' }; <form novalidate #f="ngForm"> <input type='text' name='userName' placeholder='Input your userName' [(ngModel)]='model.userName'> </form> <p> {{ f.value | json }} // { "userName": "Casear" } {{ model | json }} // { "userName": "Casear" },會隨著f.value的變化而變化 </p>
這里我們不僅為ngForm.value添加了一個帶有初始值的property,還能實現(xiàn)Model和View層的聯(lián)動,盡管這種方式可能并不好,但是在某些情況下也不失為一種簡便的方案。
關于[(ngModel)]的內部邏輯可查看Angular 2 父子組件數(shù)據(jù)通信。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
- AngularJS解決ng-if中的ng-model值無效的問題
- AngularJS動態(tài)綁定ng-options的ng-model實例代碼
- AngularJS實踐之使用NgModelController進行數(shù)據(jù)綁定
- AngularJs Understanding the Model Component
- AngularJS基礎 ng-model-options 指令簡單示例
- AngularJs 彈出模態(tài)框(model)
- 深入淺析AngularJS和DataModel
- AngularJS實現(xiàn)Model緩存的方式
- angularjs自定義ng-model標簽的屬性
- angularjs在ng-repeat中使用ng-model遇到的問題
相關文章
angular5 httpclient的示例實戰(zhàn)
本篇文章主要介紹了angular5 httpclient的示例實戰(zhàn),小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-03-03AngularJs Understanding Angular Templates
本文主要介紹AngularJs Understanding Angular Templates的資料,這里整理了詳細的資料及簡單示例代碼,有興趣的小伙伴的參考下2016-09-09AngularJS數(shù)據(jù)源的多種獲取方式匯總
在AngularJS中獲取數(shù)據(jù)源的方式有很多種,本文給大家整理幾種獲取數(shù)據(jù)源的方式,對angularjs獲取數(shù)據(jù)源的方式相關知識感興趣的朋友一起學習吧2016-02-02