像javascript中的document.getElementById(“ id”),我们可以在angular2及更高版本中做什么以在类型脚本中获取dom元素?
我尝试了angular.element但它不起作用
有多种方法可以做到这一点。我将展示其中之一。
您可以使用它。
工作示例在这里
Component.ts
import { Component, ViewChild, AfterViewInit, ElementRef } from '@angular/core';
import { HelloComponent } from './hello.component';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent implements AfterViewInit {
name = 'Angular';
@ViewChild('pRef', {static: false}) pRef: ElementRef;
ngAfterViewInit() {
console.log(this.pRef.nativeElement.innerHTML);
this.pRef.nativeElement.innerHTML = "DOM updated succesfully!!!";
}
}
。html
<hello name="{{ name }}" ></hello>
<p #pRef>
Start editing to see some magic happen :)
</p>
工作示例在这里