【问题标题】:No value accessor for form control with name: 'recipient'没有名称的表单控件的值访问器:'recipient'
【发布时间】:2016-08-16 14:54:42
【问题描述】:

升级到 Angular 2 Rc.5 后出现此错误。 这是我的组件模板:

<md-input
    [(ngModel)]="recipient"
    name="recipient"
    placeholder="Name"
    class="col-sm-4"
    (blur)="addRecipient(recipient)">
</md-input>

我的 app.module.ts 导入 FormsModule

我也尝试在我的组件中声明private recipient;

我错过了什么吗?为什么会出现此错误?

No value accessor for form control with name: 'recipient'

【问题讨论】:

标签: angular typescript angular-material2


【解决方案1】:

您应该像这样将 ngDefaultControl 属性添加到您的输入中:

<md-input
    [(ngModel)]="recipient"
    name="recipient"
    placeholder="Name"
    class="col-sm-4"
    (blur)="addRecipient(recipient)"
    ngDefaultControl>
</md-input>

取自这篇文章中的 cmets:

angular2 rc.5 custom input, No value accessor for form control with unspecified name

注意:对于更高版本的@angular/material:

现在你应该改写:

<md-input-container>
    <input
        mdInput
        [(ngModel)]="recipient"
        name="recipient"
        placeholder="Name"
        (blur)="addRecipient(recipient)">
</md-input-container>

https://material.angular.io/components/input/overview

【讨论】:

  • 它适用于我,但有人可以解释一下为什么我们必须添加“ngDefaultControl”吗?
  • 那是因为 md-input 不是 ngModel 的已知标签,但是对于最新版本的 @angular/material,您应该使用带有 mdInput 作为属性的输入标签,而不是包装在 md-input-container 中元素。见material.angular.io/components/input/overview
【解决方案2】:

确保您也导入 MaterialModule,因为您使用的是不属于 FormsModule 的 md-input

【讨论】:

  • 应该安装什么 npm 包来获取 MaterialModule?
  • 我认为是@angular2-material/core
  • @angular2-material/core 中没有 MaterialModule
  • 好的,我检查过了,你需要这样做:npm install @angular2-material/core --save 和 npm install @angular2-material/input --save,然后从@angular2-material 导入 MdInputModule /输入
  • 我已经导入了 MdInputModule,但是当我将 [(ngModel)] 添加到我的 md-input 时,我收到了与问题相同的错误消息:“表单控件没有值访问器”。你用 ngModel 测试过吗? (这就是问题所指的)。
猜你喜欢
  • 2020-07-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-07
  • 1970-01-01
  • 2023-04-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多