Angular6 @ViewChild 未定义与 ngIf

标签 angular viewchild

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

...
<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:

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

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

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

最佳答案

正如 Angular 的 Doc 所说:

"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 解决问题,因为它是在 ngAfterViewInit 上访问的,而不是在 { static: true } 上访问在 ngOnInit 上运行更改检测之前访问。

关于Angular6 @ViewChild 未定义与 ngIf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55610047/

相关文章:

Angular 6 : get reference to Components created with *ngFor inside ng-container tag

javascript - AngularJS $rootScope.$on 在迁移到 Angular2 的上下文中的替代方案

javascript - 无法减少对 Angular 8 的支持

css - 我无法将内容正确居中,怎么办?

javascript - 多次实例化@ViewChild,这样我就可以再次使用HTML Angular 4

Angular 4 找不到名称 'ViewChild'

angular - 在 Angular 2 的 rxjs 中使用 switchMap 运算符时,我们是否必须取消订阅?

javascript - Angular2 Pipe 用于更改特定字符的内联样式

html - 在 Angular 6 中使用 @ViewChild 创建粘性元素 - 无法获取元素的位置

angular - 模板变量,直接在模板中读取自定义实例