文章内容

2021/6/3 11:01:11,作 者: 黄兵

It looks like you're using ngModel on the same form field as formControl.

最近在使用Angular表单的时候出现了如下警告⚠:

    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 a future version of Angular.


    For more information on this, see our API docs here:

    https://angular.io/api/forms/FormControlDirective#use-with-ngmodel

出现警告的代码:

<input matInput aria-label="State" [matAutocomplete]="auto" name="ASN" [(ngModel)]="cloudIPRangeModel.ASN" [formControl]="ASNFormControl" required>

这里formControl上使用ngModel,会出现这个警告。

直接删除ngModel指令,之后在formControl上设置值,具体做法如下:

ASNFormControl: FormControl = new FormControl(this.cloudIPRangeModel?.ASN, Validators.required);

这里在初始化formControl的时候无法加载值,所以是this.cloudIPRangeModel?.ASN防止出错。

加载值之后,设置formControl的值,具体代码如下:

this.ASNFormControl.setValue(this.cloudIPRangeModel.ASN);

这样就不会报错了。


黄兵个人博客原创。

转载请注明出处:黄兵个人博客 - It looks like you're using ngModel on the same form field as formControl.

分享到:

发表评论

评论列表