由於您使用的是反應形式,因此可以利用它。不鼓勵使用反應形式的ngModel
。在ReactiveFormsModule
ngModel
指令甚至不包括在內。
由於您有多個複選框,您應該使用FormArray
來捕獲值。我們可以稱之爲FormArray objectiveOfUtilisingServiceControls
。
然後我們有一個方法添加或刪除表單數組的項目。我們在模板中的變化事件,在此我們通過複選框的布爾值,如果它檢查與否,意義,以及我們要添加到數組形式,實際的項目:
(change)="onChange(objective.value, $event.target.checked)"
的onChange
方法是這樣的:
onChange(value:string, isChecked: boolean) {
let objectiveOfUtilisingServiceControls =
<FormArray>this.myForm.controls.objectiveOfUtilisingServiceControls;
if(isChecked) {
objectiveOfUtilisingServiceControls.push(new FormControl(value));
} else {
let index =
objectiveOfUtilisingServiceControls.controls.findIndex(x => x.value == value)
objectiveOfUtilisingServiceControls.removeAt(index);
}
}
在哪裏,我們要麼推新FormControl
的形式排列,或者它是否被選中,我們從表單刪除陣列的形式控制。
由於您有一些預選的值,我們還需要在表單數組中初始添加該值。我們可以做到這一點,我們已經建立了形式,它可以是這樣的後:(fb
指的是Formbuilder
)
ngOnInit() {
// build form
this.myForm = this.fb.group({
objectiveOfUtilisingServiceControls: this.fb.array([])
});
//iterate and check which object matches the with the value in 'userInfo.objective'
for (let obj of this.initialInformationDetails.objectiveOfUtilisingService) {
if (obj.value == this.userInfo.objective) {
this.onChange(obj.value, true)
break;
}
}
}
至於在模板中prechecked值,只需使用[checked]
:
<label *ngFor="let objective of initialInformationDetails.objectiveOfUtilisingService">
<input type="checkbox" (change)="onChange(objective.value, $event.target.checked)"
[checked]="userInfo.objective == objective.value"/> {{objective.value}}
</label>
當您提交表單時,您的表單的所有值都在myForm.value
,只需將myForm
更改爲您擁有的實際表單名稱即可。
看到這個問題,它非常接近你想要做的。 https://stackoverflow.com/q/45085453/5556177 – Nehal
你有一個反應形式?不鼓勵將它與ngModel一起使用。我想知道formcontrolname,因爲如果你想有幾個複選框,它將不能用於表單控件,因爲它只能捕獲一個值,我會說你想要一個formarray。 – Alex
嘿,這個答案是怎麼回事?無論是幫助你還是你需要進一步的幫助? :) – Alex