无法读取未定义的属性“本机元素”

新手上路,请多包涵

我正在使用离子 2。

我需要获取 HTML 元素值。

实际上,我使用了viewchild。

这是我的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 值是 firebase 值。我访问这个元素。但我没有得到元素的价值。

这是我的组件

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

      }
    }

我参考了这个链接 How can I select an element in a component template?

我尝试了很多方法。

但我收到了这个错误

Cannot read property 'nativeElement' of undefined.

原文由 ANISUNDAR 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 613
2 个回答

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

取决于你的代码我已经修改了一点。试试下面,它对我有用。

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

注意: 如果不起作用,请增加超时时间,然后重试。

原文由 Sabari 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进