How can I set the value of a native element in Angular, using Renderer2?

Donovant picture Donovant · Apr 4, 2018 · Viewed 20.4k times · Source

I'd like to set the innerText/innerHTML/textContent of a nativeElement?

this.render.setValue(this.nativeCloneLi.querySelector('.down .inn'), timeVal);

where timeVal is a string

the element is correctly selected, but setValue seems not working at all

Answer

Tomasz Kula picture Tomasz Kula · Apr 4, 2018

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