首页 > 解决方案 > Angular 4 - 反应形式 - 模糊一个字段将所有字段突出显示为红色

问题描述

对于上下文,这是我的表格:

this.commentForm = this.fb.group(
    {
        commentId: [''],
        commentType: ['', ExistsWithinList(this.commentTypes)],
        commodity: ['', ExistsWithinList(this.commodities)],
        title: ['', Validators.required],
        description: ['', Validators.required],
        dealerId: ['', Validators.required],
        operator: ['', Validators.required]
    },
    {
        updateOn: 'submit'
    }
);

   

模板:

<form [formGroup]="commentForm" (ngSubmit)="submitForm()">
    <div class="row">
        <div class="col-lg-6">
            <label for="title">Title</label>
            <input type="text" id="title" class="form-control" formControlName="title" />
        </div>
    </div>
    <br />
    <div class="row">
        <div class="col-sm-3">
            <label for="commentType">Issue Type</label>
            <select class="form-control" id="commentType" formControlName="commentType">
                <option value="">--Select Type--</option>
                <option *ngFor="let commentType of commentTypes">{{ commentType }}</option>
            </select>
        </div>
        <div class="col-sm-3">
            <label for="commodity">Commodity</label>
            <select class="form-control" id="commodity" formControlName="commodity">
                <option value="">--Select Commodity--</option>
                <option *ngFor="let commodity of commodities">{{ commodity }}</option>
            </select>
        </div>
    </div>
    <br />
    <div class="row">
        <div class="col-sm-12">
            <label for="description">Description</label>
            <textarea rows="10" class="form-control" formControlName="description" id="description">
            </textarea>
        </div>
    </div>
    <br />
    <div class="row">
        <div class="col-sm-2">
            <span *ngIf="dealerCommentCreation; else updateSubmitButtonBlock">
                <input type="submit" class="btn btn-primary" value="Report" />
            </span>
            <ng-template #updateSubmitButtonBlock>
                <input type="submit" class="btn btn-primary" value="Update" />
            </ng-template>
        </div>
    </div>
</form>

当我专注于这些字段中的任何一个,然后模糊一个字段时,所有带有“Validators.required”的字段都会突出显示红色(尽管在过去,使用较新版本的 Angular,只有一个字段突出显示红色)

不幸的是,我无法显示实际页面(由于 NDA)。

相关 Angular 依赖项的片段(在 package.json 中):

  "@angular/common": "4.4.6",
  "@angular/compiler": "4.4.6",
  "@angular/core": "4.4.6",
  "@angular/forms": "4.4.6",
  "@angular/http": "4.4.6",
  "@angular/platform-browser": "4.4.6",
  "@angular/platform-browser-dynamic": "4.4.6",
  "@angular/router": "4.4.6",

标签: angulartypescriptangular-reactive-formsangular4-forms

解决方案


更新——因此,经过进一步调查,我意识到Angular 4 的反应式表单还不支持“updateOn”属性(这是 Angular 5+ 提供的一项功能)

可能有其他方法可以更新表单的验证状态(使用 Angular 4),但由于时间限制,我迁移到了基于模板的解决方案——这个应用程序中已经建立的大多数表单都是基于模板的,并保持我们的一致的表格给了我更多的理由进行转换。

但是,我会说我更喜欢反应式表单,因为它们使自定义/异步验证更加清晰(无缝)。


推荐阅读