猿问

Angular 8 viewChild 返回未定义

我正在尝试访问 childView 实例,但它一直说 childView 未定义。


这是我的 childViews 代码:


@ViewChild(CreateQuestionnaireComponent,{ read: true, static: false })  private childQuestionnaireDialog:CreateQuestionnaireComponent;

@ViewChild(ProjectNavbarComponent,{ read: true, static: false })  private childProjectNavBar:ProjectNavbarComponent;

@ViewChild(QuestionnaireNodeComponent,{ read: true, static: false }) private childQuestionnaireNode:QuestionnaireNodeComponent;

....


onCreateTerminal() {

        this.childQuestionnaireDialog.generateQuestionnaireDropDownList();

        this.childQuestionnaireDialog.resetFields();

        this._hideQuestionnaireDialog = false;

        this._modalTitle = 'New Terminal';

        this._placeHolderText = 'Terminal Questionnaire Title';

        this._terminal = true;

    }

...


它说:this.childQuestionnaireDialog 是未定义的”。


它正在使用 Angular 7。


根据我的新知识,@viewChild 采用一个名为 static 的标志。如果我们将该标志设置为 true,则父组件会在其自己的创建过程中尝试获取对 childView 的引用。换句话说,我们可以在父组件的 onInit() 方法中有一个 childView 的实例。基本上是一次访问,因为我们将无法在任何其他方法中访问。


设置为false的标志,基本上是ivy渲染器中的新方式。


就我而言,这两个选项都不起作用。


函数式编程
浏览 188回答 3
3回答

慕村225694

我有一个类似的问题,其中 ViewChild 组件在 onInit() 方法中未定义。// Ensure Change Detection runs before accessing the instance@ContentChild('foo', { static: false }) foo!: ElementRef;// If you need to access it in ngOnInit hook@ViewChild(TemplateRef, { static: true }) foo!: TemplateRef;

富国沪深

就我而言,我让我的孩子处于 *ngIf 状态。因此 ViewChild 无法初始化所需的元素。更新了在 *ngIf 之外渲染组件的逻辑,因此 ViewChild 能够成功初始化元素。因此,如果可能,当需要 ViewChild 时,更改逻辑以在 *ngIf 之外呈现组件并显示适当的消息。或者使用 CSS 隐藏元素的可见性,而不是使用 *ngIf。
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答