我想在角4中实现类似的东西。
$('dataBlock').empty();
如何使用组件中的ID访问DOM元素?当我尝试以下操作时,我得到了一个错误消息 Cannot read property 'nativeElement' of undefined
Cannot read property 'nativeElement' of undefined
<div id="dataBlock"></div>
组件.ts
@ViewChild('dataBlock') block: ElementRef; getGraphdata(){ **code to get data and implement a graph** this.dataBlock.nativeElement.empty(); }
您可以使用标准的javascript方法通过 id :
id
document.getElementById("dataBlock").innerHTML = "";
然而,在角度上,引用元素的首选方法是 template reference variable :
<div #dataBlock></div> <button (click)="dataBlock.innerHTML = ''">Clear content</button>
该变量还允许在 @ViewChild :
@ViewChild
@ViewChild("dataBlock") block: ElementRef; clearContent() { this.block.nativeElement.innerHTML = ""; }