Answer the question
In order to leave comments, you need to log in
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)
});
}
}
<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>
Answer the question
In order to leave comments, you need to log in
Something like this? - https://stackblitz.com/edit/angular-2oejmz
Idea taken from here
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question