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

2

24

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

Wallache answered 4/4, 2018 at 15:21 Comment(2)
How do you create nativeCloneLi?Uund
Using an ElementRef instance.nativeElementWallache
L
38

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

Legion answered 4/4, 2018 at 15:33 Comment(3)
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;Disinclination
@Disinclination I'm also curious, should we use the renderer if we just want to read the element.Lightness
@abyrne85, @Lightness 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) to get anything from DOM.Ceiling
B
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);
  }
}
Bauble answered 12/1, 2020 at 12:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.