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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With