繁体   English   中英

错误:没有NgControl Angular AOT的提供者

[英]ERROR in : No provider for NgControl Angular AOT

我正在尝试实现一个自定义ControlValueAccessor,因为Kara Erickson在最后一个Angular Connect https://youtu.be/CD_t3m2WMM8?t=20m22s上推荐。 将有效状态从父组件传递给子组件。

app.component.html:

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

国家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>

国家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的提供者(“[错误 - >] <app-country-select> </ app-country-select>”)

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

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

将依赖项标记为可选的参数元数据。 如果未找到依赖项,则Injector提供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;
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM