Skip to content

Instantly share code, notes, and snippets.

@dachi023
Last active February 7, 2024 08:13
Show Gist options
  • Save dachi023/86ea80614254fa4c25c3808cf444fca9 to your computer and use it in GitHub Desktop.
Save dachi023/86ea80614254fa4c25c3808cf444fca9 to your computer and use it in GitHub Desktop.
How to control multiple checkboxes in Angular
<label *ngFor="let control of form.controls.liquors.controls; let i = index">
<input type="checkbox" [formControl]="control"></input>
<span>{{ liquors[i].label }}</span>
</label>
import { Component, OnInit } from "@angular/core";
import { FormArray, FormBuilder, FormControl, FormGroup } from "@angular/forms";
const Liquors: { id: number; label: string; }[] = [
{ id: 1, label: "Beer" },
{ id: 2, label: "Whisky" },
{ id: 3, label: "Wine" },
]
@Component({
templateUrl: "./my.component.html",
})
export class MyComponent implements OnInit {
readonly liquors = Liquors;
form: FormGroup<{ liquors: FormArray<FormControl<boolean>> }>;
constructor(private fb: FormBuilder) {}
ngOnInit(): void {
this.form = this.fb.nonNullable.group({
liquors: this.fb.array(
this.liquors.map(() =>
this.fb.nonNullable.control(false),
),
),
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment