How to append dynamic DOM elements from a directive in Angular 2?

Use Renderer provided by Angular to manipulate the DOM:

import { DOCUMENT } from '@angular/common';

export class MyDirective implements OnInit {
  constructor(
    private elementRef: ElementRef,
    private renderer: Renderer2,
    @Inject(DOCUMENT) private document: Document) { }

  ngOnInit() {
    const child = this.document.createElement('div');
    this.renderer.appendChild(this.elementRef.nativeElement, child);
  }
}

This doesn’t depend on the native DOM API like appendChild(), so in a way it’s a platform-independent approach.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)