I am trying to add my array of object to map the primeng checkbox and would like to get the values for selected check boxes.
I have tried FormControlName but it it's throwing undefined after submitting.
below is the rough code
data = [
{ type: dropdown
text: 'drop',
num: 1.23,
options: [
{
value=1,
text= 'drop1
},{
value=2,
text= 'drop2
}
]
},
{ type: checkbox
text: 'check',
num: 1.23,
options: [
{
value=1,
text= 'check1
},{
value=2,
text= 'check2
}
]
},
{ type: radio
text: 'radio',
num: 1.23,
options: [
{
value=1,
text= 'radio1
},{
value=2,
text= 'radio2
}
]
},
];
Template:
<form [formGroup]="group">
<div *ngFor="let d of data">
<div *ngSwitchCase = "checkbox">
<p-checkbox *ngFor="let check of options" [value]="check.value" [formControlName]="check.text"></p-checkbox>
</div>
<div *ngSwitchCase = "dropdown">
<p-dropdown *ngFor="let drop of options" [value]="drop.value" [formControlName]="d.text"> {{drop.text}}
</p-dropdown>
</div>
<div *ngSwitchCase = "radio">
<p-radioButton *ngFor="let radio of options"[value]="radio.value" [formControlName]="d.text"></p-radioButton >
</div>
</div>
</form>
How I can get the reference of my control and values the same for drop down and check boxes.
How to get the values for dynamic forms?
for reactive dynamic form first thing we have to generate the formGroup base of the form control data
getFormGroup method will return a formGroup object by loop over the data and create a form controls with name base of the text
value .
getFormGroup() {
const formControls = this.data.reduce( (controls , f:FormControl)=>{
controls[f.text] = this.formBuilder.control(null);
return controls;
},{});
return this.formBuilder.group(formControls)
}
after we generate the form now we can render the form controls on the template
<form [formGroup]="form">
<div *ngFor="let d of data">
<ng-container [ngSwitch]="d.type">
<label for="">{{d.text}}</label>
<div *ngSwitchCase="'checkbox'">
<p-checkbox *ngFor="let check of d.options" [label]="check.label" [value]="check.value"
[formControlName]="d.text"></p-checkbox>
</div>
<div *ngSwitchCase="'dropdown'">
<p-dropdown [options]="d.options" [formControlName]="d.text">
</p-dropdown>
</div>
<div *ngSwitchCase="'radio'">
<p-radioButton *ngFor="let radio of d.options" [name]="d.text" [label]="radio.label"
[value]="radio.value" [formControlName]="d.text">
</p-radioButton>
</div>
</ng-container>
</div>
</form>
stackblitz demo 🚀
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