我用的是离子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);
}
}
我参考了这个链接如何选择组件模板中的元素? https://stackoverflow.com/questions/32693061/angular-2-typescript-get-hold-of-an-element-in-the-template/32693892
我尝试了很多方法。
但我收到这个错误
Cannot read property 'nativeElement' of undefined.
我认为您正在尝试在完全渲染之前从 html 获取值。如果您尝试通过单击按钮来打印该值,它将起作用。
取决于你的代码,我修改了一点。尝试下面的方法,它对我有用。
ngAfterViewInit() {
console.log("afterinit");
setTimeout(() => {
console.log(this.abc.nativeElement.innerText);
}, 1000);
}
Note:如果不起作用,请增加超时时间并重试。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)