Angular 2 @ViewChild returns undefined

后端 未结 6 1219
南旧
南旧 2020-12-15 02:57

I\'ve looked at several related posts and documentation, but still can\'t seem to get expected behavior from @ViewChild.

Ultimately, I\'m trying to set the scroll p

6条回答
  •  情歌与酒
    2020-12-15 03:24

    Sometimes, if the component isn’t yet initialized when you access it, you get an error that says that the child component is undefined.

    However, even if you access to the child component in the AfterViewInit, sometimes the @ViewChild was still returning null. The problem can be caused by the *ngIf or other directive.

    The solution is to use the @ViewChildren instead of @ViewChild and subscribe the changes subscription that is executed when the component is ready.

    For example, if in the parent component ParentComponent you want to access the child component MyComponent.

    import { Component, ViewChildren, AfterViewInit, QueryList } from '@angular/core';
    import { MyComponent } from './mycomponent.component';
    
    export class ParentComponent implements AfterViewInit
    {
      //other code emitted for clarity
    
      @ViewChildren(MyComponent) childrenComponent: QueryList;
    
      public ngAfterViewInit(): void
      {
        this.childrenComponent.changes.subscribe((comps: QueryList) =>
        {
          // Now you can access the child component
        });
      }
    }
    

提交回复
热议问题