23

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

Donovant
  • 3,091
  • 8
  • 40
  • 68

2 Answers2

35

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

Tomasz Kula
  • 16,199
  • 2
  • 68
  • 79
  • Should we also use renderer if we just want to read a value on the native element, for instance const top = this._elementRef.nativeElement.getBoundingClientRect().top; – abyrne85 Oct 17 '18 at 11:09
  • @abyrne85 I'm also curious, should we use the renderer if we just want to read the element. – calbear47 Nov 29 '18 at 14:39
  • 2
    @abyrne85, @calbear47 No, there is no need to. `Renderer2` provides a API to manipulate native elements in platform agnostic manner. Meaning it's releasing you from direct DOM access and allowing you operate on it in abstract way. But as long as you only read and not changing anything you can use native element directly (if access to them is supported) or provide custom `Renderer2` implementation with features you are missing. Actually Angular doesn't provide any support (except `ElementRef` and [events](https://angular.io/api/core/Renderer2#listen)) to get anything from DOM. – Bardr Feb 07 '19 at 15:02
1

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);
  }
}
Manish
  • 1,946
  • 2
  • 24
  • 36