SGN SGN - 3 months ago 172
TypeScript Question

TypeScript - Append HTML to container element in Angular 2

What I want to do, is simply append some html on an element.
I checked some links, and i find different confusing/non-working/non-recomended/etc solutions.

Using javascript I'll do something like this

var d1 = document.getElementsByClassName('one');
d1.insertAdjacentHTML('beforeend', '<div class="two">two</div>');


How do I achieve the same result using typescript/angular2, RC5 ?

EDIT

The element with class
.one
is generated by an external js, and I can't modify it

Answer

1.

<div class="one" [innerHtml]="htmlToAdd"></div>
this.htmlToAdd = '<div class="two">two</div>';

See also In RC.1 some styles can't be added using binding syntax

  1. Alternatively
<div class="one" #one></div>
@ViewChild('one') d1:ElementRef;

ngAfterViewInit() {
  d1.nativeElement.insertAdjacentHTML('beforeend', '<div class="two">two</div>');
}

or to prevent direct DOM access:

constructor(private renderer:Renderer) {}

@ViewChild('one') d1:ElementRef;

ngAfterViewInit() {
  this.renderer.invokeElementMethod(this.d1.nativeElement', 'insertAdjacentHTML' ['beforeend', '<div class="two">two</div>']);
}
    3.
constructor(private elementRef:ElementRef) {}

ngAfterViewInit() {
  var d1 = this.elementRef.nativeElement.querySelector('.one');
  d1.nativeElement.insertAdjacentHTML('beforeend', '<div class="two">two</div>');
}
Comments