[英]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?我想设置 nativeElement 的innerText/innerHTML/textContent?
this.render.setValue(this.nativeCloneLi.querySelector('.down .inn'), timeVal);
where timeVal is a string其中timeVal是一个字符串
the element is correctly selected, but setValue seems not working at all元素被正确选择,但setValue似乎根本不起作用
You need to use renderer.setProperty()
instead of renderer.setValue()
.您需要使用
renderer.setProperty()
而不是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>');
}
}
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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.