2

我有一个使用 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=时使表单无效{}

4

1 回答 1

1

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

[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

于 2016-12-12T19:56:30.527 回答