Last active
February 7, 2024 08:13
-
-
Save dachi023/86ea80614254fa4c25c3808cf444fca9 to your computer and use it in GitHub Desktop.
How to control multiple checkboxes in Angular
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<label *ngFor="let control of form.controls.liquors.controls; let i = index"> | |
<input type="checkbox" [formControl]="control"></input> | |
<span>{{ liquors[i].label }}</span> | |
</label> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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