javascriptangulardomangular-renderer2

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


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


Solution

  • 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