@viewChild not working - cannot read property nativeElement of undefined

cannot read property 'nativeelement' of undefined ionic 4
cannot read property 'nativeelement' of undefined mat-table
error typeerror cannot read property 'nativeelement' of undefined angular 9
cannot read property 'nativeelement' of undefined ngx-editor
viewchild cannot read property of undefined
nativeelement cannot read property focus of undefined
cannot read property 'viewcontainer' of undefined
core js 3864 error typeerror cannot read property nativeelement of undefined

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 this type.

However I get the error:

TypeError: Cannot read property 'nativeElement' of undefined

I try to console.log the nativeElement in ngAfterViewInit() so that it is loaded but it still throws the error.

I also access nativeElement in the click event handler, so that I can focus the element when another element is clicked - is this possibly what is mucking it up, because it compiles before the view has loaded?.

eg:

ngAfterViewInit() {
    console.log(this.keywordsInput.nativeElement); // throws an error
}

focusKeywordsInput(){
    this.keywordsInput.nativeElement.focus();
}

full Code:

relevant part of the html template being used:

<div id="keywords-button" class="form-group" (click)="focusKeywordsInput()">
    <input formControlName="keywords" id="keywords-input" placeholder="KEYWORDS (optional)"/>
    <div class="form-control-icon" id="keywords-icon"></div>
</div>

component.ts:

import { Component, OnInit, AfterViewInit, ViewChild, ElementRef } from '@angular/core';
import {  REACTIVE_FORM_DIRECTIVES, 
          FormGroup, 
          FormBuilder, 
          Validators,
          ControlValueAccessor
        } from '@angular/forms';
import { NumberPickerComponent } from './number-picker.component';
import { DistanceUnitsComponent } from './distance-units.component';
import { MapDemoComponent } from '../shared/map-demo.component';
import { AreaComponent } from './area-picker.component';
import { GoComponent } from './go.component';
import { HighlightDirective } from '../highlight.directive';

@Component({
   selector: 'find-form',
   templateUrl: 'app/find-page/find-form.component.html',
   styleUrls: ['app/find-page/find-form.component.css'],
   directives: [REACTIVE_FORM_DIRECTIVES, 
                NumberPickerComponent, 
                DistanceUnitsComponent, 
                MapDemoComponent, 
                AreaComponent, 
                GoComponent]
})
export class FindFormComponent implements OnInit, AfterViewInit {
   findForm: FormGroup;
   submitted: boolean; // keep track on whether form is submitted
   events: any[] = []; // use later to display form changes
   @ViewChild('keywords-input') keywordsInput;
//comment
   constructor(private formBuilder: FormBuilder, el: ElementRef) {}

   ngOnInit() {
      this.findForm = this.formBuilder.group({
         firstname: ['', [ Validators.required, Validators.minLength(5) ] ],
         lastname: ['', Validators.required],
         keywords: [],
         area: ['', Validators.required],
         address: this.formBuilder.group({
            street: [],
            zip: [],
            city: []
         })
      });

      this.findForm.valueChanges.subscribe(data => console.log('form changes', data));
   }

     ngAfterViewInit() {
    console.log(this.keywordsInput.nativeElement); // throws an error
  }

   focusKeywordsInput(){
      this.keywordsInput.nativeElement.focus();
   }

   save(isValid: boolean) {
      this.submitted = true;
      // check if model is valid
      // if valid, call API to save customer
      console.log(isValid);
   }
}

full html template (probably irrelevant):

<form class="text-uppercase" [formGroup]="findForm" (ngSubmit)="save(findForm.value, findForm.valid)">
    <div class="row is-heading">
        <div class="col-sm-8 offset-sm-2 col-md-6 offset-md-3 col-lg-4 offset-lg-4 input-group">
            <h2 class="search-filter-heading heading m-x-auto">find vegan</h2>
        </div>
    </div>
    <div class="row has-error-text">
        <div class="col-sm-8 offset-sm-2 col-md-6 offset-md-3 col-lg-4 offset-lg-4 input-group btn-group" style="height:64px;">
            <div style="position: relative; display: inline-block; width: 100%;">
                <multiselect #multiselect></multiselect>
            </div>
        </div>
    </div>
    <div class="row error-text"  [style.display]="multiselect.selectedCategories.length < 1 && submitted ? 'block' : 'none'">
        <div class="col-sm-8 offset-sm-2 col-md-6 offset-md-3 col-lg-4 offset-lg-4 form-group input-group btn-group">
            <small>Please select at least 1 category.</small>
        </div>
    </div>
    <div class="row is-heading">
        <div class="col-sm-8 offset-sm-2 col-md-6 offset-md-3 col-lg-4 offset-lg-4 input-group">
            <h2 class="search-filter-heading heading m-x-auto">within</h2>
        </div>
    </div>
    <div class="row">
        <div class="col-sm-8 offset-sm-2 col-md-6 offset-md-3 col-lg-4 offset-lg-4 input-group btn-group" style="height:64px;">
            <div style="position: relative; display: inline-block;">
                <number-picker #numberPicker></number-picker>
            </div>
            <distance-units></distance-units>
        </div>
    </div>
    <div class="row is-heading">
        <div class="col-sm-8 offset-sm-2 col-md-6 offset-md-3 col-lg-4 offset-lg-4 input-group">
            <h2 class="search-filter-heading heading m-x-auto">of</h2>
        </div>
    </div>
    <div class="row has-error-text">
        <div class="col-sm-8 offset-sm-2 col-md-6 offset-md-3 col-lg-4 offset-lg-4 input-group btn-group" style="height:64px;">
            <div style="position: relative; display: inline-block; width: 100%;">
                <my-area></my-area>
            </div>
        </div>
    </div>
    <div class="row error-text"  [style.display]="multiselect.selectedCategories.length < 1 && submitted ? 'block' : 'none'">
        <div class="col-sm-8 offset-sm-2 col-md-6 offset-md-3 col-lg-4 offset-lg-4 form-group input-group btn-group">
            <small [hidden]="findForm.controls.firstname.valid || (findForm.controls.firstname.pristine && !submitted)">Please enter an area.</small>
        </div>
    </div>
    <div class="row is-heading">
        <div class="col-sm-8 offset-sm-2 col-md-6 offset-md-3 col-lg-4 offset-lg-4 input-group">
            <h2 class="search-filter-heading heading m-x-auto">keywords</h2>
        </div>
    </div>
    <div class="row form-group">
        <div class="col-sm-8 offset-sm-2 col-md-6 offset-md-3 col-lg-4 offset-lg-4 input-group btn-group" style="height:64px;">
            <div style="position: relative; display: inline-block; width: 100%;">
                <div id="keywords-button" class="form-group" (click)="focusKeywordsInput()">
                    <input formControlName="keywords" id="keywords-input" placeholder="KEYWORDS (optional)"/>
                    <div class="form-control-icon" id="keywords-icon"></div>
                </div>
            </div>
        </div>
    </div>
    <div class="row">
        <div class="col-sm-8 offset-sm-2 col-md-6 offset-md-3 col-lg-4 offset-lg-4 input-group btn-group" style="height:64px;">
            <div style="position: relative; display: inline-block; width: 100%;">
                <go></go>
            </div>
        </div>
    </div>
</form>

@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

Angular2: Cannot read property 'nativeElement' of undefined · Issue , So I've been trying to use the @ViewChild('grid') approach with ngAfterViewInit() , but that isn't working. I've tried ngAfterContentInit() as well w/  @ViewChild('alert', { read: ElementRef }) alert:ElementRef; See also angular 2 / typescript : get hold of an element in the template In your case I guess you need two different @ViewChild() one for the component reference to be able to access the show() method, and a 2nd one to be able to access DOM attributes.

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>

Cannot read property 'nativeElement' of undefined when View is , Cannot read property 'nativeElement' of undefined when View is undefined # I don't know why it isn't working in my project but it's working in the demo. @​ViewChild('content')content : ElementRef; public downloadPDF(){  Angular 4 cannot read property nativeElement of undefined using ViewChild. @viewChild not working - cannot read property nativeElement of undefined. 30.

it just simple :import this directory

import {Component, Directive, Input, ViewChild} from '@angular/core';

Cannot read property 'nativeElement' of undefined and , Cannot read property 'nativeElement' of undefined and IntegrationError: We @​ViewChild('cardElement', {static: false}) cardElement: ElementRef; stripe: stripe. If you run into any issues in the book and want to ask me questions, I'm only  After the upgrade, @ViewChild directive started to give off error, such that it must have a second argument, which I made as {static : false} (following instructions on stackoverflow). This comment has been minimized.

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();
 }

TypeError: Cannot read property 'nativeElement' of undefined in , TypeError: Cannot read property 'nativeElement' of undefined in HTML5 Canvas with Ionic 2 · ionic · ionic-v3 import { Component,ViewChild,ElementRef} from '@angular/core'; export class HomePage It was working. @viewChild return undefined. Cannot read property 'nativeElement' of undefined` Wpf Font Style Not Working in RunTime and don't show correct view of my font

Cannot read property 'nativeElement' of undefined - html, I'm getting the error Cannot read property 'nativeElement' of undefined I have as any); I think I need to not use #viewChild because it is not a component but am need to use the same name. this will work: constructor(private el:ElementRef)  @ViewChild('nameForMaterialElement', {read: ElementRef}) private nameForMaterialElement: ElementRef; The reason is that md-radio-button is an angular component (which itself is a directive) and ViewChild returns the whole component if you do not specify the read option 👍

Angular #ViewChild Error 'Cannot read property nativeElement of , Angular #ViewChild Error 'Cannot read property nativeElement of undefined" So what you can do is, hiding the graph when the data is not loaded. Add the following code in your html, it should work <ng-template #abc> <div #xyz> </div>​  @igorgiovannini The reason that your example doesn't work is that you're trying to access the results of a ViewChild query before the view has completed initializing. This is why your code works in the ngAfterViewInit hook (after view inits) and not the ngOnInit hook (before view inits).

TypeError: Cannot read property 'nativeElement' of undefined Ionic-v4, I try a few solutions but those are isn't working. page.ts. import { Component, OnInit, ViewChild, ElementRef } from '@angular/core'; import  TypeError: Cannot read property 'nativeElement' of undefined at MaptransportPage.ngOnInit (maptransport.page.ts:43) C'est l'erreur que je rencontre dans l’exécution de mon code. import { Component, OnInit, ViewChild } from '@angular/core'; import { ActionSheetController, Platform, AlertController } from '@ionic/angular'; import {GoogleMaps

Comments
  • If it is not set before, how do you set it after?
  • If you mean keywordsInput, then you don't set it yourself, it's set by Angulars change detection.
  • using ngAfterViewInit() did the job!
  • Hint worked!!! Don't set "keywordsInput" before ngAfterViewInit() is called.
  • How to access field if its hidden via ng-If ? As viewChild is showing undefined even when ngIf is true.
  • @AnilUttani I don't remember what I did with this example, but can you use ngShow instead?
  • @user2023861 You can use [class.show]="showSomething" or an inverse logic [class.hide]="!showSomething".
  • I ran into this when my input element was in a Material Tab component, in the tab that was not visible by default (when the parent component loads). Solved it by moving code from ngAfterView to the event handler that runs when the relevant tab becomes active.