如果您正在使用Angular 9或以上版本,则renderer从@angular/core中删除,改为使用Renderer2。如果您已将Renderer2指定给视图容器组件的构造函数,并尝试使用其setStyle()方法,但不起作用,则可能是因为您的渲染器不在渲染器数组中。
为了解决这个问题,您需要调用viewref.Service as ViewContainerRef的createView()方法,并将一个组件创建并注册到该容器中。然后,将该组件注入依赖项中,现在您可以使用它的render 属性来访问renderer的数组,并使用setStyle()方法来设置它的样式属性。以下是代码示例:
import { Component, ViewContainerRef, Renderer2, ElementRef } from '@angular/core';
@Component({
selector: 'my-component',
template: `
My div
`
})
export class MyComponent {
constructor(
private viewContainerRef: ViewContainerRef,
private renderer: Renderer2,
private el: ElementRef
) {}
ngAfterViewInit() {
const divRef = this.el.nativeElement.querySelector('#myDiv');
const newComp = this.viewContainerRef.createComponent(this.dynamicComponent);
newComp.instance.someVal = 'some value';
// This line is important
this.renderer.appendChild(divRef, newComp.location.nativeElement);
this.renderer.setStyle(divRef, 'color', 'red');
}
dynamicComponent = class {
someVal = null;
constructor() {}
};
}