@viewChild not working - cannot read property nativeElement of undefined

后端 未结 8 1862
孤街浪徒
孤街浪徒 2020-12-05 06:00

I\'m trying to access a native element in order to focus on it when another element is clicked (much like the html attribute \"for\" - for cannot be used on elements of th

相关标签:
8条回答
  • 2020-12-05 06:38

    Initializing the Canvas like below works for TypeScript/Angular solutions.

    const canvas = <HTMLCanvasElement> document.getElementById("htmlElemId"); 
    
    const context = canvas.getContext("2d"); 
    
    0 讨论(0)
  • 2020-12-05 06:40

    You'll also get this error if your target element is inside a hidden element. If this is your HTML:

    <div *ngIf="false">
        <span #sp>Hello World</span>
    </div>
    

    Your @ViewChild('sp') sp will be undefined.

    Solution

    In such a case, then don't use *ngIf.

    Instead use a class to show/hide your element being hidden.

    <div [class.show]="shouldShow">...</div>
    
    0 讨论(0)
  • 2020-12-05 06:45

    @ViewChild('keywords-input') keywordsInput; doesn't match id="keywords-input"

    id="keywords-input"
    

    should be instead a template variable:

    #keywordsInput
    

    Note that camel case should be used, since - is not allowed in template reference names.

    @ViewChild() supports names of template variables as string:

    @ViewChild('keywordsInput') keywordsInput;
    

    or component or directive types:

    @ViewChild(MyKeywordsInputComponent) keywordsInput;
    

    See also https://stackoverflow.com/a/35209681/217408

    Hint:
    keywordsInput is not set before ngAfterViewInit() is called

    0 讨论(0)
  • 2020-12-05 06:47

    it just simple :import this directory

    import {Component, Directive, Input, ViewChild} from '@angular/core';
    
    0 讨论(0)
  • 2020-12-05 06:48

    What happens is when these elements are called before the DOM is loaded these kind of errors come up. Always use:

     window.onload = function(){
         this.keywordsInput.nativeElement.focus();
     }
    
    0 讨论(0)
  • 2020-12-05 06:52

    The accepted answer is correct in all means and I stumbled upon this thread after I couldn't get the Google Map render in one of my app components.

    Now, if you are on a recent angular version i.e. 7+ of angular then you will have to deal with the following ViewChild declaration i.e.

    @ViewChild(selector: string | Function | Type<any>, opts: {
    read?: any;
    static: boolean;
    })
    

    Now, the interesting part is the static value, which by definition says

    • static - True to resolve query results before change detection runs

    Now for rendering a map, I used the following ,

    @ViewChild('map', { static: true }) mapElement: any;
      map: google.maps.Map;
    
    0 讨论(0)
提交回复
热议问题