我正在尝试按照 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/