Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 958
Donovant Avatar asked Apr 04 '18 15:04

Donovant


People also ask

How do you get an element in Renderer2?

Using Renderer2 Use ElementRef & ViewChild to get the reference to the DOM element, which you want to manipulate. @ViewChild('hello', { static: false }) divHello: ElementRef; Use the methods like setProperty , setStyle etc to change the property, styles of the element as shown below.

What is Renderer2 in Angular?

The Renderer2 class is an abstraction provided by Angular in the form of a service that allows to manipulate elements of your app without having to touch the DOM directly.

Why would you use Renderer methods instead of using native element methods?

Using the Renderer for manipulating the DOM doesn't break server-side rendering or Web Workers (where direct access to the DOM would break). ElementRef is a class that can hold a reference to a DOM element. This is again an abstraction to not break in environments where the browsers DOM isn't actually available.

Is Renderer2 deprecated?

The Renderer class has been marked as deprecated since Angular version 4. This section provides guidance on migrating from this deprecated API to the newer Renderer2 API and what it means for your app.


2 Answers

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

like image 152
Tomasz Kula Avatar answered Sep 18 '22 17:09

Tomasz Kula


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);
  }
}
like image 26
Manish Avatar answered Sep 19 '22 17:09

Manish