如何添加“类"宿主元素? [英] How to add "class" to host element?

查看:32
本文介绍了如何添加“类"宿主元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道如何向我的组件 添加一个动态 class 属性,但在模板 html (component.html).

I dont't know how to add to my component <component></component> a dynamic class attribute but inside the template html (component.html).

我找到的唯一解决方案是通过ElementRef"本机元素修改项目.该解决方案似乎有点复杂,但要做一些应该非常简单的事情.

The only solution I found is to modify the item via "ElementRef" native element. That solution seems a little complicated to do something that should be very simple.

另一个问题是 CSS 必须在组件范围之外定义,从而破坏了组件封装.

Another problem is that CSS has to be defined outside component scope, breaking component encapsulation.

有更简单的解决方案吗?类似于 .... </root> 在模板中.

Is there a simpler solution? Something like <root [class]="..."> .... </ root> inside the template.

推荐答案

这样就不需要在组件外添加 CSS:

This way you don't need to add the CSS outside of the component:

@Component({
   selector: 'body',
   template: 'app-element',
   // prefer decorators (see below)
   // host:     {'[class.someClass]':'someField'}
})
export class App implements OnInit {
  constructor(private cdRef:ChangeDetectorRef) {}
  
  someField: boolean = false;
  // alternatively also the host parameter in the @Component()` decorator can be used
  @HostBinding('class.someClass') someField: boolean = false;

  ngOnInit() {
    this.someField = true; // set class `someClass` on `<body>`
    //this.cdRef.detectChanges(); 
  }
}

Plunker 示例

这个 CSS 是在组件内部定义的,只有在宿主元素上设置了类 someClass 时才应用选择器(从外部):

This CSS is defined inside the component and the selector is only applied if the class someClass is set on the host element (from outside):

:host(.someClass) {
  background-color: red;
}

这篇关于如何添加“类"宿主元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆