1. Angular ElementRef 简介
- ElementRef 咱们就能够封装不同平台下视图层中的 native 元素 (在浏览器环境中,native 元素通常是指 DOM 元素)
- console.dir()能够显示一个对象的所有属性和办法
- 操作dom第一种办法
constructor(private elementRef: ElementRef) {//先获取 my-app元素,而后利用 querySelector API 就能获取页面中 div 元素 let divEle = this.elementRef.nativeElement.querySelector('div'); console.dir(divEle); }
@ViewChild('greet') greetDiv: ElementRef; ngAfterViewInit() { this.greetDiv.nativeElement.style.backgroundColor = 'red'; }
constructor(private elementRef: ElementRef, private renderer: Renderer2) { } ngAfterViewInit() { // this.greetDiv.nativeElement.style.backgroundColor = 'red'; this.renderer.setStyle(this.greetDiv.nativeElement, 'backgroundColor', 'red'); }