Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have an Angular 1.x directive that appends an element. In short:

app.directive('mydirective', function() {
  template: '<ng-transclude></ng-transclude>',
  link: function(el) {
    var child = angular.element("<div/>");
    el.append(child);
  }

I can migrate this directive to Angular 2 like this:

@Directive({
  selector: '[mydirective']
})
export class MyDirective implements OnInit {
  constructor(private elementRef: ElementRef) { }

  ngOnit() {
    var child = angular.element("<div/>");
    this.elementRef.nativeElement.append(child);
  }
}

What's troubling me is this remark in the nativeElement official documentation:

Use this API as the last resource when direct access to DOM is needed.

My question is - how could I properly migrate this directive to Angular 2? My only requirement is to build an element dynamically and append it to the element with the directive.

like image 989
user11081980 Avatar asked Jul 13 '17 15:07

user11081980


People also ask

How does Angular manipulate DOM?

Manipulating the DOM is easy with Angular. We can directly access the element by using ElementRef provided by @angular/core . If you manipulate it by using a directive (common use case) — most are likely to use nativeElement directly like this: It will correctly change the color of the element.

What is DOM in angular8?

Angular 8 directives are DOM elements to interact with your application. Generally, directive is a TypeScript function. When this function executes Angular compiler checked it inside DOM element.

What is used to manipulate the DOM by creating elements in Angular?

EVENT BINDING : The flow of information from elements in a component to the corresponding component's class is event binding (HTML Template to TS) . Event binding works without having to define a template reference variable. This is the best and the easiest method to manipulate DOM elements.


1 Answers

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.

like image 138
Max Koretskyi Avatar answered Oct 13 '22 09:10

Max Koretskyi