无法读取未定义的属性“本机元素" [英] Cannot read property 'native-element' of undefined

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

问题描述

我正在使用离子 2.

我需要获取 HTML 元素值.

I need to get HTML element value.

其实我用的是viewchild.

Actually, 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 the 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.

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

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