Cannot read property 'nativeElement' of undefined


I am using ionic 2.

I need get htmlelement value.

Acutally i used viewchild.

Here is my html template code

<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>{{ | amDateFormat:'LL'}}</p>


     </div> value is firebase value. I access this element.But i didn't get the value of element.

Here is my component

import {Component, ElementRef,ViewChild, OnInit} from '@angular/core';

    export class ChatPage   {
      @ViewChild(Content) content: Content;
      @ViewChild('abc')abc: ElementRef;




I refered this link angular 2 / typescript : get hold of an element in the template

I tried to many way.

But i am getting this err

Cannot read property 'nativeElement' of undefined.
Problem courtesy of: ANISUNDAR


I think you are tring to get the value from html before rendering completely. If you try to print the value in a button click, it will works.

depend on your code I have modified a little.Try the below, it is working for me.

  ngAfterViewInit() {
    setTimeout(() => {
    }, 1000);

Note: If not working, please increase the timeout time and try again.

Solution courtesy of: Sabari


I think you should move your code from ngAfterViewInit to ngOnInit in order to avoid such kind of issues and not rely on timeout:

Discussion courtesy of: Prerak Tiwari

Do not specify the type of variable abc. It should be like below:

 @ViewChild('abc') abc;
Discussion courtesy of: Yuvraj Patil

This recipe can be found in it's original form on Stack Over Flow.