Angular 2 Form - disable submit when ngModel = empty obj

2.2k Views Asked by At

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 = {}

1

There are 1 best solutions below

1
On BEST ANSWER

Two ways, call a function to check if the value is empty (potentially expensive, probably overcomplicated):

[disabled]="f.invalid || isEmpty(f.value)"

isEmpty(formValue) {
  let x = JSON.parse(JSON.stringify(formValue));
  return Object.getOwnPropertyNames(x).length === 0;
}

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:

dirty : boolean A control is dirty if the user has changed the value in the UI.

Note that programmatic changes to a control's value will not mark it dirty.

[disabled]="!f.valid || !f.dirty"

https://angular.io/docs/ts/latest/api/forms/index/AbstractControl-class.html#!#dirty-anchor

Plunker demo: http://plnkr.co/edit/14yQk2QKgBFGLMBJYFgf?p=preview