javascript 如何使用 Renderer2 在 Angular 中设置本机元素的值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/49654783/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 08:42:14  来源:igfitidea点击:

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

javascriptangulardomrenderer

提问by Donovant

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 timeValis a string

其中timeVal是一个字符串

the element is correctly selected, but setValueseems not working at all

元素被正确选择,但setValue似乎根本不起作用

回答by Tomasz Kula

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>');
  }
}

Live demo

现场演示

回答by manish

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);
  }
}