Angular6 @ViewChild未使用ngIf定义 [英] Angular6 @ViewChild undefined with ngIf

查看:452
本文介绍了Angular6 @ViewChild未使用ngIf定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在将@ViewChild与通过ngIf显示的组件一起使用时遇到问题.我找到了各种解决方案,但没有一个对我有用. 这是我的主要组件,包括多个步骤(为简洁起见,我仅在代码中显示了2个),一个用于向前导航的按钮和一个用于重置在第一步返回的组件的按钮.第一步显示在页面打开上:

I've a problem using @ViewChild with a component showed through ngIf. I found various solutions but no one usefull for me. This is my main component, consisting of various step (I showed only 2 in code for brevity) with a button for forward navigation and a button to reset the component returning on first step. First step is showed on page opening:

...
<div class="my-container">
    <first-child *ngIf="showFirtChild"></first-child>
    <second-child *ngIf="showSecondChild"></second-child>
</div>
<button (click)="goToNextStep()"></button>
<button (click)="reset()"></button>
...

export class MainComponent implements OnInit {
    @ViewChild(FirstChild) private firstChildComp: MyFirstChildComponent;
    showFirtChild: boolean = true;

    ngOnInit() {
        //here firstChildComp is defined
    }

    //code for navigate through steps
    reset() {
        this.showFirtChild= true;
        this.firstChildComp.fillTable(); //fillTable is a function defined in MyFirstChildComponent
    }
...
}

在步骤导航期间,对firstChildComp的引用丢失,并且调用reset()时,childComp结果未定义.我知道原因是ngIf,所以我尝试使用ngAfterViewInit:

During steps navigation the reference to firstChildComp is lost and when reset() is called, childComp results undefined. I know the cause is ngIf, so I tryed to use ngAfterViewInit:

ngAfterViewInit() {
    this.fcomp = this.firstChildComp;
}

reset() {
        this.showFirtChild= true;
        this.fcomp .fillTable();
}

但是它不能解决我的问题. 有什么建议吗?

but it doesn't resolve my problem. Any suggestion?

推荐答案

如Angular的文档所述:

As Angular's Doc says:

在更改检测运行之前正确解析查询结果.如果任何查询结果在嵌套视图中(例如* ngIf),则 运行更改检测后,查询就会解决."

"True to resolve query results before change detection runs. If any query results are inside a nested view (such as *ngIf), the query is resolved after change detection runs."

因此,将参数{ static: false }传递给@ViewChild可以解决此问题,因为在ngOnInit上运行更改检测之前,可以在ngAfterViewInit上访问它,而在{ static: true }上可以访问它.

So, passing the param { static: false } to @ViewChild resolve the problem, as it is accessed on ngAfterViewInit, instead on { static: true } is accessed before change detection runs so on ngOnInit.

这篇关于Angular6 @ViewChild未使用ngIf定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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