I have an dynamic array of department list fetched from server. I want to push that array to form array on initialization, basically i want to show checkboxes based on department name or id in array. I know how to push an empty array in reactive forms.but how to initialize with an existing array.Actually its an update/edit Component
departmentList:any=[]; //array contains all departments
SelectedDeptList:any=[]; //fetched from db , selected departments
userForm: FormGroup;
this.userForm = this.fb.group({ //fb form builder
'phone': [null],
'departmentList': this.fb.array([this.createDepartment()]),
})
createDepartment(): FormGroup {
return this.fb.group({
'name': ''//checkbox value true or false
});
}
Template
<div formArrayName="departmentList" *ngFor="let item of
userForm.get('departmentList').controls; let i = index;">
<div class="col-md-6" [formGroupName]="i">
<div class="form-group">
<div class="col-md-4">
<label class="mt-checkbox mt-checkbox-outline">
<input formControlName="name" type="checkbox"> Department Name
<span></span>
</label>
</div>
</div>
</div>
</div>
ToDo ?
thanks in advance , any suggestion will be appreciated.
try this, prepare an array of object that contain selected and non selected element
let departmentControl = <FormArray>this.userForm.controls.departmentList;
this.yourArray.forEach(department => {
departmentControl.push(this.fb.group({name: department.name}))
})
Try This..
let departmentControl = this.form.get('departmentList') as FormArray).controls;
then when you receive response from server then do
I am assuming data in the form of array in data['departmentListdata']
data['departmentListdata'].forEach((department) => { this.departmentList.push(this.createDepartment(department))
});
To pre-populate data, there are two methods of FormGroup instance. setValue()
& patchValue()
. After you receive the response from the server just set/patch the values using one of these methods setValue()
and patchValue()
both sets the value in form control
of FormGroup
. setValue()
sets the value for each and every form control of FormGroup. you cannot omit any form control in setValue()
but if you want to assign only few form controls of FormGroup then you can use patchValue().
UpdateForm(){
this.userForm.setValue(
{
'phone' : '112345',//some Value
'departmentList': this.this.departmentList
});
}
OR use patchValue()
. If you want to update a partcular formControl
UpdateForm(){
this.userForm.patchValue(
{
'departmentList': this.departmentList
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With