如何解决如何在Angular中获取viewChild的innerHTML的值?
我需要Angular中的viewChild值,以检查它是否为空字符串。
我的ViewChild看起来像这样:
@ViewChild('myItem',{ static: true }) myItem: ElementRef;
我得到这样的值:
console.log('itemType',this.myItem.nativeElement.firstChild); // returns "TESTSTRING"
在控制台中,值看起来像这样:“ TESTSTRING”,它是一个字符串,但是如果我用typeof进行检查,它说它是一个对象:
console.log('itemType',typeof this.myItem.nativeElement.firstChild); // returns object
我想这样检查:
this.myItemIsEmpty = this.myItem.nativeElement.firstChild === ''; // returns always false
我在做什么错了?
解决方法
以下部分this.myItem.nativeElement.firstChild
返回类型为ChildNode
的元素-代表DOM元素。要获取其文本,您需要使用textContent
属性。
@Component({/* ...*/})
export class MyComponent implements AfterViewInit {
@ViewChild('myItem',{ static: true }) myItem: ElementRef;
// Only try to access @ViewChild/@ContentChild in/after AfterViewInit as DOM might not be rendered otherwise
public ngAfterViewInit():void {
this.myItemIsEmpty = this.myItem.nativeElement.firstChild.textContent === '';
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。