Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angular2 group of checkboxes with required attribute

i want to create a template-driven form in Angular2 (RC5), that will include a group of check-boxes, bounded to specific attributes of an object. Right now, i have such group, bounded to the corresponding array like:

<div class="checkbox" *ngFor="let prop of properties">
  <label>
    <input type="checkbox" name="option" id="option [(ngModel)]="prop.state"/> 
    {{prop.name}}
  </label>
</div>

Although this is pretty straightforward, i cannot figure out how to add a required attribute to this group of check-boxes. What i mean by that, is that i need to force user to select AT LEAST one of the group check-boxes, otherwise form validation will fail.

Any ideas?

like image 787
billias Avatar asked Sep 01 '16 17:09

billias


1 Answers

I assume you have an object or array with all of your states, if I'm reading correctly, i.e.

properties = [
  { state: false },
  { state: false },
  { state: false },
  // ... etc
];

You could figure out if at least one is checked by listening to (ngModelChange) on each of the elements. When it fires, you can then check to make sure at least one of prop's states is true, i.e. in your template file:

<input type="checkbox" name="option" id="option" [(ngModel)]="prop.state" (ngModelChange)="onCheckboxChange()"/> 

And in your class, have a field like atLeastOnePropIsTrue, and then your onCheckboxChange function can look like this:

function onCheckboxChange() {
    this.atLeastOnePropIsTrue = this.properties.find(a => a.state === true) != null;
}

It's not exactly pretty, but it would work.

like image 144
Michael Fedora Avatar answered Oct 07 '22 17:10

Michael Fedora