Hot For Coding
Angular8错误 ngModel isn't a known property

Angular8

很早之前,我和我的团队就已经使用Angular1做项目,在当时来说它的确解决了很多问题。然而Angular2与Angular1差别太大,Angular2等于憋了一个超级大招,可惜没人接招。于是大部分开始转去使用React、Vue或其它的框架了。

最近,我又开始使用Angular8开始做项目,但在一个Radio组件上绑定ngModel属性时,直接报错

Console output

ERROR Error: Uncaught (in promise): Error: Template parse errors:
Can't bind to 'ngModel' since it isn't a known property of 'mat-radio-group'.
1. If 'mat-radio-group' is an Angular component and it has 'ngModel' input, then verify that it is part of this module.
2. If 'mat-radio-group' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.
3. To allow any property add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component. ("rank-radio-group-label">对比类型,</label>
    <mat-radio-group aria-labelledby="rank-radio-group-label" [ERROR ->][(ngModel)]="selectedType" (change)="render()">
      <mat-radio-button class="rank-type" [disabled]="): ng:///PackageRankModule/NpmComponent.html@7:62
Error: Template parse errors:
Can't bind to 'ngModel' since it isn't a known property of 'mat-radio-group'.
1. If 'mat-radio-group' is an Angular component and it has 'ngModel' input, then verify that it is part of this module.
2. If 'mat-radio-group' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.
3. To allow any property add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component. ("rank-radio-group-label">对比类型,</label>
    <mat-radio-group aria-labelledby="rank-radio-group-label" [ERROR ->][(ngModel)]="selectedType" (change)="render()">
      <mat-radio-button class="rank-type" [disabled]="): ng:///PackageRankModule/NpmComponent.html@7:62

简单来说,就是一句话

Can't bind to 'ngModel' since it isn't a known property of 'mat-radio-group'.

提示ngModel不是一个已知的属性。这是什么情况?我确定我没有看错,也没有拼错,就是提示ngModel不是已知的属性。

后来查询文档,才知道Angular1之后到今天的Angular8又是突飞猛进,有些概念性的东西已经不同于早前版本,总之在Angular最新版本里,要使用ngModel在表单组件上,需要提前在module里处理一下

app.module.ts

import { FormsModule } from '@angular/forms';

[...]

@NgModule({
  imports: [
    [...]
    FormsModule
  ],
  [...]
})

按照以上代码修改module文件以后错误消失,Radio单选也可以正常工作了。

TITLE: Angular8错误 ngModel isn't a known property

LINK: https://www.qttc.net/510_angular8_error_ngmodel_is_not_known_property.html

NOTE: 转载内容请注明出处