SGN SGN - 1 year ago 931
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 ?


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

Answer Source


<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>']);
constructor(private elementRef:ElementRef) {}

ngAfterViewInit() {
  var d1 = this.elementRef.nativeElement.querySelector('.one');
  d1.nativeElement.insertAdjacentHTML('beforeend', '<div class="two">two</div>');
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download