为了能够支持跨平台,angular通过抽象层封装了不同平台的差异。
正确操作DOM的方式(用ElementRef和Renderer2)这篇文章将讲述如何使用Renderer2来操作DOM元素。我们可以使用Renderer2对元素的class和style属性进行操作,也可以对元素进行增加、删除、和插入等操作。
使用的技术:
1. angular4.2.4
2. TypeScript2.3.3
3. NodeJs6.10.1
4. Angular CLI 1.3.1
5. Angular Compiler CLI 4.2.4
一. createElement()、createText、appendChild()
createElement(name: string, namespace?: string|null): any
createText(value: string): any
appendChild(parent: any, child: any): void
例子:
import { Component, ElementRef, Renderer2, ViewChild } from '@angular/core';
@Component({
selector: 'app-append',
templateUrl: './append-demo.component.html'
})
export class AppendDemoComponent {
@ViewChild('div') private d1: ElementRef;
constructor(private renderer: Renderer2) {
}
onClick() {
const li = this.renderer.createElement('li');
const text = this.renderer.createText('Click here to add li');
this.renderer.appendChild(li, text);
this.renderer.appendChild(this.d1.nativeElement, li);
}
}
二、insertBefore()
insertBefore(parent: any, newChild: any, refChild: any): void
例子:
import { Component, ViewChild, ElementRef, Renderer2 } from '@angular/core';
@Component({
selector: 'app-insertBefore',
templateUrl: './insertBefore.component.html',
styleUrls: ['./insertBefore.component.css']