Angular 4 - ngModel for select and select multiple checkboxes

In application there are 4 checkboxes. When i select one box all gets selected and when i deselct any one all gets deselcted. I want the top box to control all boxes below like if i check top box as select then all should select. if i unselect top all should get unselected. and below one's should be independent of each other. If i select all down boxes then main top box one should also get selected.

//our root app component
import {Component, NgModule, VERSION} from '@angular/core'
import {FormsModule} from '@angular/forms'
import {BrowserModule} from '@angular/platform-browser'

  selector: 'my-app',
  providers: [],
  template: `
  <input type="checkbox" [(ngModel)]="theCheckbox"  data-md-icheck (change)="toggleVisibility($event)"/><br>
  <input type="checkbox"  [(ngModel)]="theCheckbox" /><br>
  <input type="checkbox" [(ngModel)]="theCheckbox" /><br>
  <input type="checkbox" [(ngModel)]="theCheckbox" /><br>
  Checkbox is <span *ngIf="marked">checked</span><span *ngIf="!marked">unchecked</span>

  <div>And <b>ngModel</b> also works, it's value is <b>{{theCheckbox}}</b></div>

  directives: []
export class App {
  marked = false;
  theCheckbox = false;
  constructor() {



  imports: [ BrowserModule , FormsModule],
  declarations: [ App ],
  bootstrap: [ App ]
export class AppModule {}

1 answer

  • answered 2018-03-13 20:59 DiabolicWords

    First of all you have to be aware of the fact that you cannot use "theCheckbox" as ngModel for all your checkboxes. To keep your app simple, you should start with one variable for each checkbox. e.g.:

    export class App {
       marked = false;
       masterCheckbox = false;
       slaveCheckbox1 = false;
       slaveCheckbox2 = false;
       slaveCheckbox3 = false;
       constructor() { }

    And in your HTML

      <input type="checkbox" [(ngModel)]="masterCheckbox"  data-md-icheck (change)="toggleVisibility($event)"/><br>
      <input type="checkbox" [(ngModel)]="slaveCheckbox1" /><br>
      <input type="checkbox" [(ngModel)]="slaveCheckbox2" /><br>
      <input type="checkbox" [(ngModel)]="slaveCheckbox3" /><br>

    This will solve your problem that, no matter which box you click, all of them get changed.

    Next you have to implement the method that (de)selects all slave-boxes by clicking the master-box. Even here just a basic example:

    In your typescript file:

    private toggleEntireItemSelection(): void {
       this.slaveCheckbox1 = this.marked;
       this.slaveCheckbox2 = this.marked;
       this.slaveCheckbox3 = this.marked;

    and you call this method from


    I'm quit sure that you'll find the solution for your last question yourself. ;-)