如何添加“类"?托管元素? [英] How to add "class" to host element?
问题描述
我不知道如何在组件html(component.html)内添加动态 class 属性到组件<component></component>
.
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 [class]="..."> .... </ root>
之类的东西.
Is there a simpler solution? Something like <root [class]="..."> .... </ root>
inside the template.
推荐答案
@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();
}
}
这样,您无需在组件外部添加CSS. CSS之类的
This way you don't need to add the CSS outside of the component. CSS like
:host(.someClass) {
background-color: red;
}
从组件内部开始工作,只有在宿主元素上设置了类someClass
时,才应用选择器.
works from the inside of the component and the selector is only applied if the class someClass
is set on the host element.
这篇关于如何添加“类"?托管元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!