如果我在 HTML 中包含一个组件并通过 DI 注入它,为什么会出现 StaticInjector 错误

Why do I get StaticInjector error if I include a component both in HTML as well as inject it via DI

我有一个使用 LoginFormComponent 的组件 ValidateSessionComponent。我在 ValidateSessionComponent 中使用 LoginFormComponent,方法是将其包含在 ValidateSessionComponent 的 HTML 中。

目前为止一切正常。然后我决定在 ValidateSessionComponent

中也通过 DI 包含对 LoginFormComponent 的引用
constructor(private loginForm2:LoginFormComponent,private helper:HelperService,private dialogService:DialogBoxService,private activatedRoute:ActivatedRoute, private router:Router, private userManagementService:UserManagementService) { }

这开始导致错误 StaticInjectorError(DynamicTestModule)[ValidateSessionComponent -> LoginFormComponent]: StaticInjectorError(Platform: core)[ValidateSessionComponent -> LoginFormComponent]: NullInjectorError: No provider for LoginFormComponent!

为什么我开始收到错误消息?

因为 DI 仅适用于提供商。

组件不是提供者。

如果您希望获得对子元素的引用,请改用 ViewChild

@ViewChild(LoginFormComponent, { static: true }) loginForm: LoginFormComponent;