ElementRef

提供对底层原生元素(DOM元素)的访问。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import { AfterContentInit, Component, ElementRef } from '@angular/core';

@Component({
selector: 'app-root',
template: `
<h1>My App</h1>
<pre>
<code>{{ node }}</code>
</pre>
`
})
export class AppComponent implements AfterContentInit {
node: string;

constructor(private elementRef: ElementRef) { }

ngAfterContentInit() {
const tmp = document.createElement('div');
const el = this.elementRef.nativeElement.cloneNode(true);

tmp.appendChild(el);
this.node = tmp.innerHTML;
}

}

View Example