为了账号安全,请及时绑定邮箱和手机立即绑定

Angular 8 viewChild 返回未定义

Angular 8 viewChild 返回未定义

函数式编程 2021-06-09 17:49:40
我正在尝试访问 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渲染器中的新方式。就我而言,这两个选项都不起作用。
查看完整描述

3 回答

?
慕村225694

TA贡献1880条经验 获得超4个赞

我有一个类似的问题,其中 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;


查看完整回答
反对 回复 2021-06-18
?
富国沪深

TA贡献1790条经验 获得超9个赞

就我而言,我让我的孩子处于 *ngIf 状态。因此 ViewChild 无法初始化所需的元素。更新了在 *ngIf 之外渲染组件的逻辑,因此 ViewChild 能够成功初始化元素。

因此,如果可能,当需要 ViewChild 时,更改逻辑以在 *ngIf 之外呈现组件并显示适当的消息。或者使用 CSS 隐藏元素的可见性,而不是使用 *ngIf。


查看完整回答
反对 回复 2021-06-18
  • 3 回答
  • 0 关注
  • 187 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信