首页 > 解决方案 > 通过 formGroup + ngModel 使用的角度反应式表单验证:弃用的致命警告 + 移除支持?

问题描述

我的网页 HTML 上有一个简单的文本输入,我想在输入中包含动态表单验证,如下所示:

    <mat-form-field>
      <mat-label>Chosen Name:</mat-label>
      <input name="chosenName" formControlName="chosenName" [(ngModel)]="chosenName" matInput type="text" placeholder="JOHN DOE"/>
      <mat-hint align="end">REQUIRED FIELD!</mat-hint>
      <mat-error *ngIf="hasNameError('chosenName', 'required')"
        >Minimum and Maxmimum of length 12 is required!</mat-error
      >
    </mat-form-field>

chosenName是在我的 component.ts 中声明的字符串变量,我通过 [(ngModel)] 接受它,至少我确定它是这样工作的

一切运行良好,我能够让验证器正常工作。我唯一担心的是控制台显示此错误:

It looks like you're using ngModel on the same form field as formControl. 
    Support for using the ngModel input property and ngModelChange event with 
    reactive form directives has been deprecated in Angular v6 and will be removed 
    in Angular v7.

这是我应该特别担心的事情吗?如果是这样,有人可以指出我更好的实施吗?

标签: angularvalidationangular-reactive-forms

解决方案


我不认为你在伤害它,但避免这样做总是好的做法。当您在单页中处理大量控件时,请始终使用 FormGroup。


推荐阅读