Hello Devs,
In this tutorial, we will learn Checkbox Checked Event in Angular Example
Here you will learn checkbox change event in angular. So, let's follow few step to create example of angular checkbox change event example.
Follow this step by step guide below.
Step 1: 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 { }
Step 2: 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>
Step 3: 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: 'rathorji.in' },
{ id: 2, name: 'rathorji.in' },
{ id: 3, name: 'rathorji.in' }
];
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);
}
}
May this example help you.