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

时间:2016-12-12 19:34:12

标签: javascript angular typescript angular2-ngmodel

我有一个使用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 = {}

时使表单无效

1 个答案:

答案 0 :(得分:1)

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

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

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

stringify和parse一起删除任何未定义的键(继续,console.log(formValue)并查看那些未定义的键!)

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

  

dirty:boolean如果用户更改了值,则控件是脏的   在用户界面。

     

请注意,对控件值的编程更改不会标记它   脏。

[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