Enable one checkbox at a time in angular2
Enable one checkbox at a time in angular2
I am generating multiple checkboxes dynamically using ngFor. But here i need to enable one checkbox at a time, if one is checked the other checkboxes need to be disabled. Similarly if i uncheck the checkbox other checkboxes need to be enabled. How to achieve this in angular2?
<div class="col-12 mb-2" *ngFor="let option of question.options; let i = index;">
<input type="checkbox"
[(ngModel)]="question.options[i].correct"
[disabled]="!question.options[i].correct && i != activeIndex"
(ngModelChange)="copyQuestionmarks(i)">
</div>
In the code i am disabling the checkbox if its not a correct option and if that is not the active index. This works only for the first time, Suppose if i uncheck this other checkboxes won't get enabled.
Below is my .ts code
public copyQuestionmarks(i: number)
this.activeIndex = i;
Help appreciated!
1 Answer
1
in your component:
public copyQuestionmarks(i: number)
this.activeIndex = this.activeIndex === i ? i : undefined;
and in the template:
[disabled]="!question.options[i].correct && i !== activeIndex"
Explanation: The activeIndex is set every time you check the box, but you never reset the activeIndex. In the template we also need for the type of the activeIndex, because index 0 != undefined
would return false.
I am sure there is even a much cleaner solution for those checkboxes.
0 != undefined
Further more you don't have to write question.options[i].correct
u can also archive the same effect by using option.correct
, that was initalized in the ngfor loop before.
question.options[i].correct
option.correct
Thanks for contributing an answer to Stack Overflow!
But avoid …
To learn more, see our tips on writing great answers.
Some of your past answers have not been well-received, and you're in danger of being blocked from answering.
Please pay close attention to the following guidance:
But avoid …
To learn more, see our tips on writing great answers.
Required, but never shown
Required, but never shown
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.