Angular 库组件在使用它的应用程序中导致引用错误

Angular library component causes Reference Error in the application that uses it

我收到以下错误:

Uncaught ReferenceError: Cannot access 'SomeLibraryComponent' before initialization

我有一个库模块/工作区,我使用 package.json 依赖项创建并导入到我的应用程序项目/工作区,并导入到我的应用程序主模块定义中。

调查堆栈跟踪后,我发现这是由于尝试初始化另一个组件的 ViewChild 'SomeParentLibraryComponent':

@Component({
    selector:'some-parent',
    templateUrl: './some-parent.component.html'
})
export class SomeParentLibraryComponent {
    
    @ViewChild(SomeLibraryComponent, {static: false}) theCauseComponent: SomeLibraryComponent;
    .....
}

@Component({
    selector:'some-child',
    templateUrl: './some.component.html'
})
export class SomeLibraryComponent {
    .....
}

模板文件'./some-parent.component.ts':

<div>
    ...
    <some-child></some-child>
    ...
</div>

如何解决这个问题?为什么会这样?

我正在使用 Angular 11。应用程序项目(angular 工作区 1)和库项目(angular 工作区 2)都是使用 angular-cli 生成的

问题的解决方法是用 HTML 中的引用名称替换类型。 在父组件(./some-parent.component.html)的模板文件中,添加对子组件的引用:

<div>
    ...
    <some-child #theChild></some-child>
    ...
</div>

在父类的打字稿文件 (*.ts) 中,将引用从类型更改为命名:

@ViewChild('theChild', {static: false}) theCauseComponent: SomeLibraryComponent;

我不知道为什么会这样,但这解决了问题。

您使用的是 static false,因此您只能在 AfterViewInit 中访问它。如果您想在 AfterViewInit 之前使用或在您的组件中实现 AfterViewInit 并在 ngAfterViewInit

中使用它,请使用 static true