【问题标题】:Angular library component causes Reference Error in the application that uses itAngular 库组件在使用它的应用程序中导致引用错误
【发布时间】:2021-04-29 23:25:05
【问题描述】:

我收到以下错误:

未捕获的 ReferenceError:在初始化之前无法访问“SomeLibraryComponent”

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

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

@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。应用程序项目(角度工作区 1)和库项目(角度工作区 2)都是使用 angular-cli 生成的

【问题讨论】:

    标签: angular angular-cli angular11


    【解决方案1】:

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

    【讨论】:

    【解决方案2】:

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

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

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

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

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

    【讨论】:

      猜你喜欢
      • 2021-11-24
      • 1970-01-01
      • 1970-01-01
      • 2020-04-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-17
      • 1970-01-01
      相关资源
      最近更新 更多