angular多選表單數(shù)據(jù)綁定的簡單嘗試
前言
對于一個多選類型,如何獲取所有已選擇的數(shù)組。
嘗試
獲取formControl的value。
this.formControl.valueChanges.subscribe(value => { console.log(value); })
對于綁定多選類型的formControl的value,只會有true或者false。
如果你選中就是true,如果不選中就是false。但是我想要的是所有選中對象數(shù)組。
谷歌搜索得知,可以綁定點擊事件,再去增加或刪除數(shù)組中的對象。
<div *ngFor="let option of formItem.formItemOptions; index as i" class="form-check"> <input [formControl]="formControl" [value]="option.id" (click)="selectCheckBox(formControl.value, option)" class="form-check-input" type="checkbox" > <label class="form-check-label mr-1" for="{{id}}_{{option.id}}"> <span>{{option.content}}</span> </label> </div>
selectCheckBox(isCheck: boolean, option: FormItemOption): void { if (isCheck) { this.formItemValue.formItemOptions.push(option); } else { const index = this.formItemValue.formItemOptions.indexOf(option); this.formItemValue.formItemOptions.splice(index, 1); } }
但是獲取傳入的formControl.value變量為null,猜測可能先出發(fā)點擊時間,后進行表單數(shù)據(jù)綁定。
改寫方法
selectCheckBox(isCheck: boolean, option: FormItemOption): void { // 如果index值為-2,表示數(shù)組為定義,創(chuàng)造一個數(shù)組 // 如果index值為-1,表示所選選項并未處于數(shù)組內(nèi),添加之 // 如果index值大于等于0,筆試所選選項處于數(shù)組內(nèi),刪除之 const index = Array.isArray(this.formItemValue.formItemOptions) ? this.formItemValue.formItemOptions.indexOf(option) : -2; if (index < -1) { this.formItemValue.formItemOptions = [option]; } else if (index < 0) { this.formItemValue.formItemOptions.push(option); } else { this.formItemValue.formItemOptions.splice(index, 1); } }
測試
但是如果多選題本身就有對象數(shù)組,如何初始化。
想著用input 標(biāo)簽的checked="checked"
屬性確定初始化選項,發(fā)現(xiàn)并未生效,去除input標(biāo)簽的[formControl]="formControl"
后,就生效了,猜測可能兩個屬性沖突。
查看博客上實例,對于每一個選項綁定一個formControl。定義一個FormArray整合所有formControl。如果有需要可以嘗試。
https://stackoverflow.com/questions/40927167/angular-reactiveforms-producing-an-array-of-checkbox-values/69637536#69637536
總結(jié)
到此這篇關(guān)于angular多選表單數(shù)據(jù)綁定的文章就介紹到這了,更多相關(guān)angular多選表單數(shù)據(jù)綁定內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
詳解Angular.js數(shù)據(jù)綁定時自動轉(zhuǎn)義html標(biāo)簽及內(nèi)容
本篇文章主要介紹了詳解Angular.js數(shù)據(jù)綁定時自動轉(zhuǎn)義html標(biāo)簽及內(nèi)容 ,具有一定的參考價值,感興趣的小伙伴們可以參考一下。2017-03-03AngularJS實現(xiàn)的輸入框字?jǐn)?shù)限制提醒功能示例
這篇文章主要介紹了AngularJS實現(xiàn)的輸入框字?jǐn)?shù)限制提醒功能,涉及AngularJS事件監(jiān)聽與元素屬性動態(tài)操作相關(guān)實現(xiàn)技巧,需要的朋友可以參考下2017-10-10angularjs1.5 組件內(nèi)用函數(shù)向外傳值的實例
今天小編就為大家分享一篇angularjs1.5 組件內(nèi)用函數(shù)向外傳值的實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-09-09

Angular directive遞歸實現(xiàn)目錄樹結(jié)構(gòu)代碼實例

AngularJS service之select下拉菜單效果

AngularJs定時器$interval 和 $timeout詳解

Angular4學(xué)習(xí)筆記router的簡單使用