Hello Devs,
In this tutorial, we are going to learn checkbox example in angular 10.
In this example we will simply take website array variable with list of variable and display list of checkbox with website name.
Follow this step by step guide given below:
Import FormsModule
src/app/app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
FormsModule,
ReactiveFormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
Form with ngModel
src/app/app.component.html
<div class="container">
<h1>Angular CheckBox Example - Rathorji.in</h1>
<form [formGroup]="form" (ngSubmit)="submit()">
<div class="form-group">
<label for="website">Website:</label>
<div *ngFor="let web of websiteList">
<label>
<input type="checkbox" [value]="web.id" (change)="onCheckboxChange($event)" />
{{web.name}}
</label>
</div>
</div>
<button class="btn btn-primary" type="submit" [disabled]="!form.valid">Submit</button>
</form>
</div>
updated Ts File
src/app/app.component.ts
import { Component } from '@angular/core';
import { FormBuilder, FormGroup, FormControl, Validators, FormArray} from '@angular/forms';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
form: FormGroup;
websiteList: any = [
{ id: 1, name: 'HDTuto.com' },
{ id: 2, name: 'HDTuto.com' },
{ id: 3, name: 'NiceSnippets.com' }
];
constructor(private formBuilder: FormBuilder) {
this.form = this.formBuilder.group({
website: this.formBuilder.array([], [Validators.required])
})
}
onCheckboxChange(e) {
const website: FormArray = this.form.get('website') as FormArray;
if (e.target.checked) {
website.push(new FormControl(e.target.value));
} else {
const index = website.controls.findIndex(x => x.value === e.target.value);
website.removeAt(index);
}
}
submit(){
console.log(this.form.value);
}
}
Run this command:
ng serve
I hope this example helps you.