Angular 8 viewChild返回未定义 [英] Angular 8 viewChild returns undefined

查看:134
本文介绍了Angular 8 viewChild返回未定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to access the childView instance but it keeps saying the the childView is undefined.

这是我的childViews代码:

Here is my code for 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未定义".

It says :this.childQuestionnaireDialog is undefined".

它正在使用Angular 7.

It was working with Angular 7.

根据我的新知识,@viewChild带有一个称为static的标志.如果将标记设置为true,则父组件将在其自身创建期间尝试获取对childView的引用.换句话说,我们可以在父Component的onInit()方法中拥有childView的实例.基本上是一次访问,因为我们无法使用任何其他方法进行访问.

As per my new knowledge, the @viewChild takes a flag called static. If we put the flag to true, the parent component tries to get a reference to the childView during its own creation. In other words, we could have an instance of the childView in the onInit() method of the parent Component.Basically a one time access because we won't be able to access in any other methods.

设置为false的标志基本上是常春藤渲染器中的新方法.

The flag set to false, is basically the new way in ivy renderer.

我的问题是,这两个选项都不起作用.

The problem in my case, neither options are working.

推荐答案

我有一个类似的问题,其中在onInit()方法中未定义ViewChild组件.

I had a similar problem where ViewChild component is undefined in onInit() method.

此问题已解决:

// 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;

这篇关于Angular 8 viewChild返回未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆