W
W
WhatIsHTML2018-12-20 18:31:24
Angular
WhatIsHTML, 2018-12-20 18:31:24

How to implement a form with a list of checkboxes as one control in Angular 6?

You need to implement a form with a list of checkboxes that will be presented as one control in angular 6.
The component looks like this. As you can see, the category can come marked as true or false (in reality, the categories come from the server).

import { Component } from '@angular/core';
import { FormControl, FormBuilder } from '@angular/forms';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular 6';
  categories = [
    {
      id: 1,
      name: 'tech',
      checked: false
    },
    {
      id: 2,
      name: 'animals',
      checked: true
    },
    {
      id: 3,
      name: 'food',
      checked: false
    }
  ];

  myGroup;

  constructor(private formBuilder: FormBuilder) {
    this.myGroup = this.formBuilder.group({
      myCategory: this.formBuilder.array(this.categories)
    });
  }
}

The html looks like this
<form [formGroup]="myGroup">
  <div *ngFor="let category of myGroup.controls['myCategory'].controls; let i = index">
    <input type="checkbox" [formControl]="category" [checked]="categories[i].checked">
    <label>{{ categories[i].name }}</label>
  </div>
  Selected: <strong>{{ myGroup.get('myCategory').value }}</strong>
</form>

Here is an example https://stackblitz.com/edit/angular-1hnnxx
Everything is ok, but as soon as you click on the checkbox, the object in the categories array immediately becomes a boolean true/false. Thus, we lose information about the category in the component. Why is this happening?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Ivan Stroykin, 2018-12-20
@WhatIsHTML

Something like this? - https://stackblitz.com/edit/angular-2oejmz
Idea taken from here

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question