Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Kaidanov/678d200d0425402c92c164fcd00192ec to your computer and use it in GitHub Desktop.
Save Kaidanov/678d200d0425402c92c164fcd00192ec to your computer and use it in GitHub Desktop.
Angular 5 Reactive Forms - Checkbox array handle - mat-checkbox simple
<div class="row">
<!--First column-->
<div class="col-md-12">
<section class="checkbox-section text-center" *ngIf="notifications && notifications.length > 0">
<label class="example-margin">Notifications to send:</label>
<p *ngFor="let n of notifications" formArrayName="notification">
<mat-checkbox class="checkbox-margin" (change)="updateChkbxArray(n, $event.checked, 'notification')" value="n.id">{{n.description}}</mat-checkbox>
</p>
</section>
</div>
</div>
...
form: FormGroup
notifications: any = {}
...
//get the data - in my case code table - id, description
this.yourService.getnotifications().subscribe(response => {
this.notifications = ...;
});
...
createForm() {
this.form = this.fb.group({
firstName: ['', Validators.required],
lastName: ['', Validators.required],
...
notification: this.fb.array([]) ///formArrayName="notification" - that's the connection
});
}
///updtaes the values into the form controls - adding and removing on the click
///can be used for more that one checkbox array on one component.
updateChkbxArray(chk, isChecked, key) {
const chkArray = <FormArray>this.form.get(key);
if (isChecked) {
//sometimes inserts values already included creating double records for the same values -hence the defence
if (chkArray.controls.findIndex(x => x.value == chk.id) == -1)
chkArray.push(new FormControl({ id: chk.id, description: chk.description }));
} else {
let idx = chkArray.controls.findIndex(x => x.value == chk.id);
chkArray.removeAt(idx);
}
}
///I didn't find the way to uncheck all together when reseting the form so I went for mat-selection-list at the end.. and it looks better
import { CustomMaterialModule } from "./core/material.module";
...
@NgModule({
exports: [],
declarations: [
...
],
imports: [
..
CustomMaterialModule,
AppRoutingModule,
..
],
providers: [...
],
bootstrap: [AppComponent]
})
export class AppModule { }
import { NgModule } from "@angular/core";
import { CommonModule } from '@angular/common';
import {
MatCheckboxModule, MatListModule,//...
} from '@angular/material';
import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
const materialModules = [
///...
MatCheckboxModule,
MatListModule,
];
@NgModule({
imports: [...materialModules],
exports: [...materialModules]
})
export class CustomMaterialModule { }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment