How can I set the value of a native element in Angular, using Renderer2?
I prefer it doing this way:
import { Component, Renderer2, AfterViewInit, ElementRef, ViewChild } from '@angular/core';
@Component({
selector: 'my-app',
template: `
<div #el></div>
`,
styleUrls: [ './app.component.css' ]
})
export class AppComponent implements AfterViewInit {
@ViewChild('el') el: ElementRef;
constructor(private renderer: Renderer2) {}
ngAfterViewInit() {
const h1 = this.renderer.createElement('h1');
const text = this.renderer.createText('Hello world');
this.renderer.appendChild(h1, text);
this.renderer.appendChild(this.el.nativeElement, div);
}
}
You need to use renderer.setProperty()
instead of renderer.setValue()
.
import { Component, Renderer2, AfterViewInit, ElementRef, ViewChild } from '@angular/core';
@Component({
selector: 'my-app',
template: `
<div #el></div>
`,
styleUrls: [ './app.component.css' ]
})
export class AppComponent implements AfterViewInit {
@ViewChild('el') el: ElementRef;
constructor(private renderer: Renderer2) {}
ngAfterViewInit() {
this.renderer.setProperty(this.el.nativeElement, 'innerHTML', '<h1>Hello world</h1>');
}
}
Live demo