9

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?

2

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.