mercredi 18 novembre 2020

How to render dynamic checkbox conditionally in Reactive forms

  • I'm trying to create dynamic checkbox list conditionally on a value select Tried various solution online but unable to get the expected result.

  • Also, Facing issues with binding value to form-control

Final result is expected to be a formdata of below format on submit:

{
name:"new Experiment",
depth: 'Exp Wise", 
durationPerDepth:[{
exp:"exp1",
duration:"10mins" ]} 
}

-----OR---

{
name:"new Experiment",
depth: 'For All", 
durationPerDepth:[{
exp:"All",
duration:"10mins" ]} 
}

for_all[ ]

set_for_all=[{"exp":'all', "duration": ["2Mins", "4Mins", "10Mins"]}];

exp_wise[ ]

[
    {
        "exp":"exp1",
        "duration":[
            "2Mins", "4Mins", "10Mins"
        ]
    },
    {
        "exp":"exp2",
        "duration":[
            "2Mins", "4Mins", "10Mins"
        ]
    },
    {
        "exp":"exp3",
        "duration":[
            "2Mins", "4Mins", "10Mins"
        ]
    }
]

component.ts

ngOnInit()
this.createNew = this.formBuilder.group({
  Name: ['', Validators.required],
  depth: ['', Validators.required],
  durationAsPerDepth: this.formBuilder.array([]) 
 });

 this.createNew.get('depth').valueChanges.subscribe((depth:string) => {
if(depth){
if(depth === 'For All'){
  this.dataArr=this.for_all;
  this.addCheckboxes();
}else if(depth === 'Exp wise') {
  this.dataArr=this.exp_wise;
  this.addCheckboxes();
 }
  }})}

get durationFormArray() {
return this.createNew.controls.durationAsPerDepth as FormArray;
}

private addCheckboxes() {   
    this.dataArr.forEach(() => this.durationFormArray.push(new FormControl(false)));
   }

component.html

<section class="exp-section">
  <label class="exp-margin pl-1 mb-2" [style.font-size.px]="14">Experiment Depth</label>
  <mat-radio-group formControlName="experimentDepth">
    <mat-radio-button class="exp-margin" value="Exp wise">Experiment wise</mat-radio-button>
    <mat-radio-button class="exp-margin" value="For All" >Set for All</mat-radio-button>
  </mat-radio-group>
</section>

<div *ngIf="depth.value" class="container">
  <div formArrayName="durationAsPerDepth">
    <div *ngFor="let duration of durationFormArray.controls; let i = index">
    <section class="exp-section mt-3">
        <mat-checkbox class="exp-margin" [formControlName]="i"></mat-checkbox>
        <mat-checkbox class="exp-margin" *ngFor="let time of dataArr[i].duartion" [value]="time" [formControlName]="i"></mat-checkbox>
    </section>
    </div>
  </div>
</div>



Aucun commentaire:

Enregistrer un commentaire