无法读取未定义的属性“nativeElement” [英] Cannot read property 'nativeElement' of undefined

查看:4506
本文介绍了无法读取未定义的属性“nativeElement”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用离子2。

我需要获得htmlelement值。

I need get htmlelement value.

我实际上使用了viewchild。

Acutally i used viewchild.

这是我的html模板代码

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>{{chat.date | amDateFormat:'LL'}}</p>                 
              {{checkdate()}}                         
   </div>

chat.date值是firebase值。我访问这个元素。但我没有得到元素的值。

chat.date value is firebase value. I access this element.But i didn't get the value of element.

这是我的组件

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

      }
    }

我提到这个链接如何在组件模板中选择元素?

我尝试了很多方法。

但是我得到了这个错误

Cannot read property 'nativeElement' of undefined.


推荐答案

我认为你要从html获取价值在完全渲染之前。如果您尝试在按钮单击中打印该值,它将起作用。

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() {
    console.log("afterinit");
    setTimeout(() => {
      console.log(this.abc.nativeElement.innerText);
    }, 1000);
  }

注意:如果不能正常工作,请增加超时时间再试一次。

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

这篇关于无法读取未定义的属性“nativeElement”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆