【问题标题】:Angular ERROR in : No provider for NgControl角度错误:没有 NgControl 的提供者
【发布时间】:2019-08-12 01:21:45
【问题描述】:

我正在创建一个实现 ControlValueAccessor 的组件,以在反应式表单中使用,它只是一个输入元素的包装器,上面有一些管道。

我已注入 NgControl 以检索有效/无效状态并将它们传播到内部输入元素。

当输入值在另一个输入中找到时,无效。

Here is the Stackblitz

在 Stackblitz 上工作正常,但是当我进行 ng build --prod 时,它会引发错误:

错误:没有 NgControl 的提供程序 ("[ERROR ->])

你有什么问题吗?

谢谢!

【问题讨论】:

    标签: angular angular-reactive-forms controlvalueaccessor


    【解决方案1】:

    您好,您可以为您的 NgControl 添加“@Optional”装饰器。如果找不到提供者,它将使用 null。欲了解更多信息,请查看:https://angular.io/api/core/Optional

    在您的代码中:

    import { Component, Input, OnInit, Self,Optional } from '@angular/core';
    
    ...
          constructor(
        @Self() @Optional() private controlContainer: NgControl
      ) {
        this.controlContainer.valueAccessor = this;
      }
    

    【讨论】:

    • 哦,也许它是空的,因为我在另一点使用相同的组件,代码没有被表单包裹?!
    • 我试过了,但是 controlContailer 返回了一个空值,所以我不能调用它的 valueAccessor。如何解决?
    • 谢谢 - 这正是我遇到的问题,@Optional() 装饰器解决了这个问题。为清楚起见,使用常规的ng build 命令这不是问题,但使用ng build --prod 运行生产构建时会出现问题。
    猜你喜欢
    • 1970-01-01
    • 2018-08-08
    • 2018-03-04
    • 1970-01-01
    • 2019-04-23
    • 1970-01-01
    • 2021-05-19
    • 1970-01-01
    • 2018-06-21
    相关资源
    最近更新 更多