javascript - : No provider for NgControl Angular AOT 中的错误

标签 javascript angular angular-cli

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

应用程序组件.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>

country-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 构建时,它失败并显示消息

ERROR in : No provider for NgControl ("[ERROR ->]<app-country-select></app-country-select>")

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

最佳答案

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

A parameter metadata that marks a dependency as optional. Injector provides null if the dependency is not found.

就我而言,这解决了“No provider”错误,我能够成功编译项目。

例子:

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;
  }
}

关于javascript - : No provider for NgControl Angular AOT 中的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47886424/

相关文章:

javascript - 如何在 shadow dom 中使用全局 css 样式

javascript - 用户是否可以在不进行身份验证的情况下直接将文件上传到 Google Cloud Storage?

Angular 服务 - 返回的对象类型是对象,而不是指定的泛型类型

php - 通过在 codeigniter 中加载 View 来打开 Bootstrap 模式对话框

javascript - Observable 不发出新值

angular - Typescript "this"实例在类中未定义

angular - Infragistics:如何使用 id 显示多个 ignite Snackbar

angular - 为index.html中的src标签指定前缀

javascript - Angular karma Jasmine 错误 : Illegal state: Could not load the summary for directive

css 中的 Angular 内联资源作为 data-uri