Angular 2 @ViewChild returns undefined

▼魔方 西西 提交于 2019-12-03 22:07:29

Try using a ref in your template instead:

<div id='gallery-container' #galleryContainer class='gallery-image-container'>
    <div class='gallery-padding'></div>
    <img class='gallery-image' src='{{ coverPhotoVm }}' />
    <img class='gallery-image' src='{{ imagepath }}' *ngFor='let imagepath of imagesVm' />
</div>

And use the ref name as the argument:

@ViewChild('galleryContainer') galleryContainer: ElementRef;

EDIT

Forgot to mention that any view child thus declared is only available after the view is initialized. The first time this happens is in ngAfterViewInit (import and implement the AfterViewInit interface).

The ref name must not contain dashes or this will not work

Marco Barbero

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

  public ngAfterViewInit(): void
  {
    this.childrenComponent.changes.subscribe((comps: QueryList<MyComponent>) =>
    {
      // Now you can access the child component
    });
  }
}
Martin Stetina

Subscribing to changes on

@ViewChildren(MyComponent) childrenComponent: QueryList<MyComponent>

confirmed working, combined with setTimeout() and notifyOnChanges() and careful null checking.

Any other approach produces unreliable results and is hard to test.

I had a similar issue. Unlike you, my @ViewChild returned a valid ElementRef, but when I tried to access its nativeElement, it was undefined.

I resolved it by setting the view id like #content, not like #content = "ngModel".

<textarea type = "text"
    id = "content"
    name = "content"
    #content
    [(ngModel)] = "article.content"
    required></textarea>

I had the same problem today. Strangely using setTimeout worked for me.

give it a try:

ngAfterViewInit(){
    setTimeout(_ => console.log('My element: ' + this.galleryContainer), 0);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!