I have an Angular2 form that is created dynamically with a for loop. For this question I am concerned with the radio buttons in my form. The form is created in the HTML then from the TS I assign the ngModel of each input to an empty object. I want the submit button in my form to be disabled until a radio button is chosen:
<form (ngSubmit)="onNext(f)" #f="ngForm">
<div class="multi-choice-question-div radio-btn-div question_div"
*ngIf="question?.type === 'multi-choice' && !question?.isYesOrNo">
<div *ngFor="let answer of question?.answerDetails">
<input
type="radio"
class="display-none"
id="{{ answer?.answerId }}"
[(ngModel)]="ngModelObj['question_' + question.questionId]"
name="answerForQustion{{ question?.questionId }}"
[value]="answer"
required>
<label class="col-md-12 col-sm-12 multi-choice-label" for="{{ answer?.answerId }}">
<p class="q-text">{{ answer?.value }}</p>
</label>
</div>
</div>
<button class="btn btn-next"
type="submit"
*ngIf="currentSectionIndex < sectionsArr.length - 1"
[disabled]="!f.valid">
NEXT
</button>
</form>
Even when the client has not chosen a radio button, the form thinks that it is valid and I think this is because ngModel
for the radio input is set = to {}
.
How can I keep this same setup (because it is engrained deep into my component frontend and backend) but make the form invalid when the ngModel
= {}
Two ways, call a function to check if the value is empty (potentially expensive, probably overcomplicated):
The stringify and parse together strip out any undefined keys (go ahead,
console.log(formValue)
and look at those undefined keys!)Or you can check the form for
dirty
which indicates:https://angular.io/docs/ts/latest/api/forms/index/AbstractControl-class.html#!#dirty-anchor
Plunker demo: http://plnkr.co/edit/14yQk2QKgBFGLMBJYFgf?p=preview