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
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.
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.
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.
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.
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
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With