Angular 2 @ViewChild returns undefined

后端 未结 6 1216
南旧
南旧 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:22

    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

    0 讨论(0)
  • 2020-12-15 03:22

    This is your .ts file code for using DOM elements by ViewChild

    import { Component, AfterViewInit, ViewChild, ElementRef } from '@angular/core';
    
    @Component({
    
        selector: 'portfolio-page',
        templateUrl: './portfolio-page.component.html',
        styleUrls: ['./portfolio-page.component.scss']
    })
    
    export class PortfolioPageComponent implements AfterViewInit{
    
        @ViewChild('galleryContainer') galleryContainer: ElementRef;
    
        ngAfterViewInit(){
            console.log('My element: ' + this.galleryContainer);
        }
    }
    

    This is your .html file code

        <div #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>
    

    Hope it helps!

    0 讨论(0)
  • 2020-12-15 03:23

    Another possible scenario is when you are using typescript in angular or ionic framework and calling the ViewChild element from a function having javascript like signature. Please use a typescript like function signature instead (e.g. using fat arrow =>). For example

    accessViewChild(){
        console.log(this.galleryContainer.nativeElement.innerHTML);
    }
    

    would show print undefined however

    accessViewChild = ()=>{
        console.log(this.galleryContainer.nativeElement.innerHTML);
    }
    

    would print the inner html.

    0 讨论(0)
  • 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<MyComponent>;
    
      public ngAfterViewInit(): void
      {
        this.childrenComponent.changes.subscribe((comps: QueryList<MyComponent>) =>
        {
          // Now you can access the child component
        });
      }
    }
    
    0 讨论(0)
  • 2020-12-15 03:25

    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.

    0 讨论(0)
  • 2020-12-15 03:29

    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>
    
    0 讨论(0)
提交回复
热议问题