Angular 2 Form - 当 ngModel = empty obj 时禁用提交

Angular 2 Form - disable submit when ngModel = empty obj

我有一个使用 for 循环动态创建的 Angular2 表单。对于这个问题,我关心的是表单中的单选按钮。表单在 HTML 中创建,然后从 TS 我将每个输入的 ngModel 分配给一个空对象。我希望在选择单选按钮之前禁用表单中的提交按钮:

<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>

即使客户端没有选择单选按钮,表单也认为它是有效的,我认为这是因为单选输入的 ngModel 设置为 {}

我怎样才能保持相同的设置(因为它深入到我的组件前端和后端)但是当 ngModel = {}

时使表单无效

两种方式,调用一个函数来检查值是否为空(可能很昂贵,可能过于复杂):

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

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

字符串化和解析一起删除所有未定义的键(继续,console.log(formValue) 并查看那些未定义的键!)

或者您可以查看 dirty 的表格,其中表示:

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 演示:http://plnkr.co/edit/14yQk2QKgBFGLMBJYFgf?p=preview