user122222
user122222

Reputation: 2419

Three state checkbox with angular 2

I want to do an input box with three states: checked, unchecked and crossed(a.k.a failed) Currently, I was able to do check/uncheck and change calculations accordingly

 <input type="checkbox" [ngStyle]="{content: expression}" *ngIf="milestone?.description" [checked]="milestone?.status == 'checked'" (change)="checkMilestone(milestone,initiative, $event, '')">

However, I have trouble adding crossed (X) checkbox. Does anyone have idea how it should be done? Should I have states something like this:

states = [
    { id: 0, status: 'checked'},
    { id: 1, status: 'unchecked'},
    { id: 2, status: 'crossed'}
];

and add styles and change them accordingly? I'm not sure how to add three styles instead of two.

Upvotes: 2

Views: 8030

Answers (1)

Martin Parenteau
Martin Parenteau

Reputation: 73731

The indeterminate state of the checkbox can be set with property binding. Here is a simplified version of your markup, showing the indeterminate state binding:

<input type="checkbox" [indeterminate]="milestone?.status === 'crossed'" 
  [ngModel]="milestone?.status === 'checked'" (ngModelChange)="checkMilestone(milestone)">

The checkMilestone method could be something like this:

checkMilestone(milestone) {
  switch (milestone.status) {
    case "checked": {
      milestone.status = "unchecked";
      break;
    }
    case "unchecked": {
      milestone.status = "crossed";
      break;
    }
    case "crossed": {
      milestone.status = "checked";
      break;
    }
  }
}

See this stackblitz for a demo.

Upvotes: 14

Related Questions