首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在Angular 5中为创建的ComponentRef添加style类?

如何在Angular 5中为创建的ComponentRef添加style类?
EN

Stack Overflow用户
提问于 2018-07-28 06:13:14
回答 1查看 2.3K关注 0票数 1

我尝试在使用ViewContainerRefComponentFactoryResolver创建组件后立即向它添加一个CSS类。我希望能够根据已经添加到myViewContainerRef的其他组件来设置类。

代码语言:javascript
复制
export class ContainerComponent {

@ViewChild('myContainerRef') myContainerRef: ViewContainerRef

constructor(private factoryResolver: ComponentFactoryResolver,
            private renderer: Renderer2) {}

addComponent() {
  const componentFactory = this.factoryResolver.resolveComponentFactory(SomeBaseComponent)
  const newComponent = this.myContainerRef.createComponent(componentFactory)

  // SomeBaseComponent has been added successfully to myContainerRef
  // Want to add CSS class to the newComponent
  // None of the following statements are adding any styles
  if( someLogic()) {
    this.renderer.addClass(newComponent.location.nativeElement, 'my-css-class')
    this.renderer.addClass(newComponent.el.nativeElement, 'my-css-class')
    this.renderer.setStyle(newComponent.el.nativeElement, 'background', 'yellow')
  }
  }
}

export class SomeBaseComponent {

  constructor(public el: ElementRef) {}

}

有没有更好的方式尝试以编程方式添加样式?还有没有其他东西可以注入到SomeBaseComponent中,以便能够在这一点上添加我想要的样式,或者我应该在newComponent.instance上设置标志,并让基本组件控制自己设置什么样式?

EN

回答 1

Stack Overflow用户

发布于 2018-07-28 06:28:13

您应该添加另一个@ViewChild,它将具有ElementRef类型的read

代码语言:javascript
复制
@ViewChild("myContainerRef", {read: ElementRef}) elementRef: ElementRef;

要设置类的属性,您应该使用以下方法。

代码语言:javascript
复制
this.elementRef.nativeElement.setAttribute("class", "test")

注意:我建议将创建逻辑放在ngOnInit()方法中,放在自定义addComponent()中。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51566181

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档