Angular NgbModal 中的组件无法使用@viewchild 访问内部方法

Angular component in NgbModal cannot use @viewchild to access methods inside

我遇到了以下问题,我认为这是一个常见问题,但我无法解决它。 我有一个小的错误警报组件,它内部有一个方法来显示错误。 我在路由组件中使用它的方式是我使用@viewChild 查询来访问它的 addNewMessage 方法并且它有效。

这次我有一个来自 ng-bootstrap 的 NgbModal,我用它打开了一个组件。在此组件中,我需要使用我的错误组件来显示错误,但我无法使错误组件在模态中正确加载,我也无法使用 viewChild 访问其方法,我不确定问题出在 viewChild 或组件上由于模块配置中缺少某些内容而未加载。

这是我在路由组件中调用模态 (NewRecordingFormComponent) 的方式:

const modalRef = this.modalService.open(NewRecordingFormComponent);

这就是我在模态中使用我的错误组件的方式:

<voice-error-alert-component #alertComponent></voice-error-alert-component>

这就是组件在编译后 html 中的显示方式:

<voice-error-alert-component _ngcontent-dhb-c7=""></voice-error-alert-component>

这是我在 NewRecordingFormComponent 中使用的 viewChild 查询:

@ViewChild('alertComponent', { static: false }) alertComponent: ErrorAlertComponent;

此查询适用于路由组件。

我不知道如何让它工作,当我查看 html 时,我应该在其中看到一个 ng-for,但我在这里什么也看不到,这让我觉得这个组件不是正在编译,就像 angular 不知道它是一个组件,只是将其保留为普通 html.

我觉得我的模态组件中找不到这个组件,可能是因为我用 bootstrap 模态打开它的方式?是因为我在动态组件上使用它并且因为它没有绑定到任何未加载的路由吗?我必须手动加载 y 还是手动声明它才能在模态中使用?

我还可以在这里放什么,以便我可以得到这方面的帮助?我对这个版本的 angular 很陌生,我正在搜索,但我找不到与我看到的类似的东西,非常感谢任何帮助!!!

尝试在 ngAfterViewInit 中记录 viewchild 变量 (console.log(alertComponent);)

请回复结果

这篇文章给了我答案: https://angular-2-training-book.rangle.io/modules/feature-modules

这里真正的问题是我的组件没有加载到我的动态组件(模态)中。

原因是我有一个应用程序模块文件,然后是应用程序部分的小模块文件,通常由路由定义。

如果你想在另一个组件中使用一个组件,那么你需要将它添加到该组件的 .module 文件中。 但是如果你想要一个带有子组件的模式(动态组件),你需要在 app.module.ts 中声明该子组件,以便所有组件都可以看到它。 方法是为您需要在应用程序中公开的每个组件创建一个小的 .module 文件,以便动态加载,如下所示:

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';

import { ErrorAlertComponent } from './error-alert-component.component';

@NgModule({
  imports: [CommonModule],
  declarations: [
    ErrorAlertComponent
  ],
  providers: [],
  exports: [ErrorAlertComponent]
})
export class ErrorAlertModule {}

然后将 ErrorAlertModule 导入到您应用中的更高模块中,就这样,它就可以工作了!

感谢@mohammad omar 的帮助,欢迎随时提出任何说明!