【问题标题】:ERROR in : No provider for NgControl Angular AOT错误:没有 NgControl Angular AOT 的提供者
【发布时间】:2017-12-19 11:53:11
【问题描述】:

我正在尝试按照 Kara Erickson 在上次 Angular Connect https://youtu.be/CD_t3m2WMM8?t=20m22s 上推荐的那样实现自定义 ControlValueAccessor。将有效性状态从父组件传递给子组件。

app.component.html:

<app-country-select ngModel="model" name="country-select"></app-country-select>

国家选择.component.html:

<select [formControl]="controlDir.control" #select placeholder="Country" i18n-placeholder (click)="onTouched()"
        (change)="onChange($event.value)" [required]="required">
  <option value="at">Austria</option>
  <option value="au">Australia</option>
</select>

国家选择.component.ts:

@Component({
    selector: 'app-country-select',
    templateUrl: './country-select.component.html',
    styleUrls: ['./country-select.component.scss'],
})
export class CountrySelectComponent implements ControlValueAccessor {

    @Input() required = false;

    @ViewChild('select') select: HTMLSelectElement;

    onChange: (value: any) => void;
    onTouched: () => void;

    constructor(@Self() public controlDir: NgControl) {
      controlDir.valueAccessor = this;

    }
...
}

完整的代码在这里:https://github.com/maksymzav/ngcontrol

代码在 JIT 模式下运行时运行良好。我猜是因为在运行时它确实知道它与哪个控件一起使用:NgModel、FormControlName 或 FormControlDirective。 但是当我使用 ng build --prod 运行 AOT 构建时,它会失败并显示消息

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

有谁知道如何使这个构建成功?谢谢。

【问题讨论】:

  • 您可能忘记将生成的html包装在表单标签中。
  • 也可以看到这篇文章:stackoverflow.com/questions/37284763/…
  • @Igor,你的意思是将app.component.html中的代码包装到form标签中吗?不幸的是,这无济于事。
  • @lemmingworks,你写的帖子是关于 angular2 使用表单的方式,当没有模块时。我同时导入了 FormsModule 和 ReactiveFormsModule,所以所有指令都应该在里面。
  • 你有没有想过这个问题?

标签: javascript angular angular-cli


【解决方案1】:

您可以将@Optional() 装饰器添加到您的controlDir

将依赖项标记为可选的参数元数据。注射器 如果未找到依赖项,则提供 null。

就我而言,这解决了“无提供者”错误,并且我能够成功编译项目。

例子:

constructor(
  @Optional() // Add this decorator
  @Self()
  public controlDir: NgControl,
  private stripe: StripeService,
  private cd: ChangeDetectorRef
) {
  // Better to add some checks here since controlDir can be null
  if (controlDir) {
    controlDir.valueAccessor = this;
  }
}

【讨论】:

  • 对我来说,即使没有 aot build 也能发生这种情况,只是在正常发球中。当我添加 @Optional() 装饰器时,它显示“无法读取 null 的属性‘控制’”。我该如何解决这个问题?
猜你喜欢
  • 2019-04-23
  • 2019-08-12
  • 2015-07-26
  • 2018-04-03
  • 2018-03-16
  • 1970-01-01
  • 1970-01-01
  • 2020-02-11
  • 2018-04-24
相关资源
最近更新 更多