Harleen Kaur Arora
Harleen Kaur Arora

Reputation: 2087

How to display checkbox values on screen if it is checekd using formGroup Angular2

I am angular2 beginner. I am try to display checkbox values on screen if checkbox is checked and checkbox is unchecked so remove the value. I am use formGroup and formArray in angular2.

Html code here :-

<form [formGroup] = "testForm">

  <div formArrayName="extras">
    <span  *ngFor="let extra of extras; let i = index" formGroupName="{{i}}">
        <label class="btn btn-primary" formControlName="{{extra.value}}" btnCheckbox  [(ngModel)] = "extra.status">{{extra.display}}</label>
    </span> 
  </div>
</form>
<!-- Display values of extras -->
<div *ngIf="getFormValues?.extras">
   <span  *ngFor="let extra of getFormValues?.extras; let i = index>
     {{extra.value}}
   </span>
</div>

Component.ts code here

extras:any = [
  { value: 'good', display: 'good', status: 'false'},
  { value: 'bed', display: 'bed', status: 'false'},
  { value: 'nice', display: 'bed', status: 'false'},
]

let allextras: FormArray = new FormArray([]);
for (let i = 0; i < this.extras.length; i++) {
  let fg = new FormGroup({});
  fg.addControl(this.extras[i].value, new FormControl(false))
  allextras.push(fg)
}

this.testForm.valueChanges.subscribe( (form: any) => {
  this.getFormValues = form;
});

This code is work well but does not display value of checkbox if checked the checkbox and visa versa. Thanks!

Upvotes: 0

Views: 147

Answers (1)

Bhabani Das
Bhabani Das

Reputation: 380

The question is not very clear and you have not posted the whole code especially for the component.ts

But for the code it seems

for (let i = 0; i < this.extras.length; i++) {
  let fg = new FormGroup({});
  fg.addControl(this.extras[i].value, new FormControl(false))
  allextras.push(fg)
}

this part is causing your problem. you are never assigning the formArray to the formGroup.

I think this should help.

  this.testForm = new FormGroup({});
  this.testForm.addControl(this.extras[i].value, new FormControl(false));

But some of the things still not clear and can cause problem . if this doesn't help please post the whole code.

Upvotes: 0

Related Questions