TypeScript - Append HTML to container element in Angular 2
With the new angular class Renderer2
constructor(private renderer:Renderer2) {}
@ViewChild('one', { static: false }) d1: ElementRef;
ngAfterViewInit() {
const d2 = this.renderer.createElement('div');
const text = this.renderer.createText('two');
this.renderer.appendChild(d2, text);
this.renderer.appendChild(this.d1.nativeElement, d2);
}
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
- 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.insertAdjacentHTML('beforeend', '<div class="two">two</div>');
}