Cannot read 'native-element' property from undefined

I am using ionic 2.

I need to get the value of an HTML element.

Actually, I used viewchild.

Here is my template html

<div class="messagesholder" *ngFor="let chat of chatval | orderby:'[date]'; let last = last"> {{last ? callFunction() : ''}} <div *ngIf="chat.sender == currentuser || chat.receiver == currentuser"> <p class="chat-date" id="abc" #abc>{{chat.date | amDateFormat:'LL'}}</p> {{checkdate()}} </div> 

chat.date is a firebase value. I am accessing this item. But I did not get the value of the item.

Here is my component

 import {Component, ElementRef,ViewChild, OnInit} from '@angular/core'; export class ChatPage { @ViewChild(Content) content: Content; @ViewChild('abc')abc: ElementRef; constructor(){} ngAfterViewInit(){ console.log("afterinit"); console.log(this.abc.nativeElement.value); } } 

I referred to this link. How to select an element in a component template?

I tried in many ways.

But I get this error

 Cannot read property 'nativeElement' of undefined. 
+16
source share
5 answers

I think you are tring to get the value from html before full rendering. If you try to print a value by pressing a button, it will work.

Depends on your code, which I changed a little. Let's go below, it works for me.

  ngAfterViewInit() { console.log("afterinit"); setTimeout(() => { console.log(this.abc.nativeElement.innerText); }, 1000); } 

Note. If you are not working, increase the waiting time and try again.

+32
source

Do not specify the type of the variable abc. It should look like this:

  @ViewChild('abc') abc; 
+1
source

I think you should move the code from ngAfterViewInit to ngOnInit to avoid such problems and not rely on a timeout:

 ngOnInit(){ console.log("afterinit"); console.log(this.abc.nativeElement.value); } 
0
source

declare the selector of the child component in the HTML template of the parent component. Otherwise, the abc component object will not be initialized at run time to invoke its functions or public properties in the parent.ts file.

Child component abc:

 @Component({ selector: 'child-abc', templateUrl: './abc.component.html', styleUrls: ['./abc.component.css'], }) 

In the parent component html template, declare a child selector:

 < child-abc > < /child-abc > 
0
source

The best lifecycle hook to use is AfterContentInit, which allows scripts to find all the html content (e.g. div #map_canvas ).

 import { AfterContentInit, ViewChild } from '@angular/core'; 

In addition, some updates have been made for ViewChild, now it takes a second parameter:

 @ViewChild('map_canvas', {static: false}) map_canvas: ElementRef; 

Now you can use this hook to initialize your map:

 ngAfterContentInit() { this.loadMap(); } 
0
source

Source: https://habr.com/ru/post/1266671/


All Articles