• ElementRef

    ElementRef

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

    1. import { AfterContentInit, Component, ElementRef } from '@angular/core';
    2. @Component({
    3. selector: 'app-root',
    4. template: `
    5. <h1>My App</h1>
    6. <pre>
    7. <code>{{ node }}</code>
    8. </pre>
    9. `
    10. })
    11. export class AppComponent implements AfterContentInit {
    12. node: string;
    13. constructor(private elementRef: ElementRef) { }
    14. ngAfterContentInit() {
    15. const tmp = document.createElement('div');
    16. const el = this.elementRef.nativeElement.cloneNode(true);
    17. tmp.appendChild(el);
    18. this.node = tmp.innerHTML;
    19. }
    20. }

    View Example