错误消息会为您指明正确的方向。 您需要声明
FormGroupDirective
是提供商。 即
@Component({
...
providers: [FormGroupDirective]
});
否则,您需要在更高级别声明它,例如在您的模块中,这样您就可以在模块范围内使用它。
删除 @Host() 装饰器和额外的提供程序,它就可以工作了。
@Component({
selector: 'nested',
template: `
<div>
<p>Nested begin </p>
<p>Host contains {{hostFormGroup.directives.length}} directives:</p>
<span *ngFor="let directive of hostFormGroup.directives">{{directive.name}}</span>
<p>Nested end </p>
</div>
`,
// tried this: no error, but injected one is not the actual container
// and it containes no directive
// without it: still same error 'No provider for FormGroupDirective'
//providers: [FormGroupDirective],
})
class NestedComponent {
constructor(
private hostFormGroup: FormGroupDirective) {
}
}
// Custom
@Component({
selector: 'custom',
template: `
<div>
<p>Custom begin </p>
<p>Host contains {{hostFormGroup.directives.length}} directives:</p>
<span *ngFor="let directive of hostFormGroup.directives">{{directive.name}}</span>
<nested></nested>
<p>Custom end </p>
</div>
`,
directives: [NestedComponent],
// tried this: still same error 'No provider for FormGroupDirective'
//providers: [FormGroupDirective],
})
class CustomComponent {
constructor(
private hostFormGroup: FormGroupDirective) {
}
}
就我而言,我所有的导入和表单初始化都是正确的,只是我错误地将相同的 formControlName 给了 2 个不同的输入,这就是
NullInjectorError: No provider for FormGroupDirective!
的原因