ElementRef

Provides access to the underlying native element (DOM element).

  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

原文: https://angular-2-training-book.rangle.io/handout/advanced-components/elementref.html