无法读取未定义的属性"native-element"

ANI*_*DAR 17 typescript ionic2 angular

我正在使用离子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>
Run Code Online (Sandbox Code Playgroud)

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

      }
    }
Run Code Online (Sandbox Code Playgroud)

我引用了这个链接如何在组件模板中选择一个元素?

我试过很多方面.

但是我收到了这个错误

Cannot read property 'nativeElement' of undefined.
Run Code Online (Sandbox Code Playgroud)

Sab*_*ari 37

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

取决于你的代码我修改了一点.尝试下面,它适合我.

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

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

  • 这不是一个好的解决方案,因为问题在于 *ngIf 语句和组件生命周期。如果画布位于 DOM 中,ngAfterViewInit 应该能够分配元素 ref,但同样,设置超时是一种 hack,完全无法测试,而且是一种可怕的做法。 (6认同)

tec*_*kie 6

如果您执行以下操作,您可以将 ElementRef 与 @ViewChild 结合使用

HTML 标记

<input type="text" class="form-control" #someNameInput>
<button
  class="btn btn-primary"
  (click)="clickMe()">Click Me</button>
Run Code Online (Sandbox Code Playgroud)

在组件代码中:

@ViewChild('someNameInput',{static: true}) someNameInput: ElementRef;
Run Code Online (Sandbox Code Playgroud)

对于旧版本,它是

@ViewChild('someNameInput') someNameInput: ElementRef;
Run Code Online (Sandbox Code Playgroud)

就在 constructor() 方法之前

这是您在函数中使用它的方式

clickMe(){
console.log(this.someNameInput.nativeElement.value);
Run Code Online (Sandbox Code Playgroud)

}

如果你得到一些未定义的值,这通常意味着这是一个 JavaScript 问题并且你没有初始化。首先尝试将 ViewChild 排除在等式之外,并确保代码首先在没有它的情况下工作。然后将 ViewChild 引入混合。有点像先用邮递员测试你的 API,然后再做 Angular 代码。首先确保后端工作,然后您确定它是 Angular 代码。Angular 具有不同的页面生命周期,因此某些值仅在 onAfterViewInit 事件中可用,而在其他事件中不可用。所以你必须玩转视图周期。还没有尝试过,但我怀疑如果您尝试在 ngOnInit 方法中获取 ViewChild 的值,您将收到错误或空白值。


归档时间:

查看次数:

48768 次

最近记录:

6 年,3 月 前