angular项目中,我们都知道可以用
[class.className]="variable"
或者
[style.styleName]="styleValue"
这2种方法给组件中的元素添加动态样式。
但是如果给当前组件的标签添加动态样式呢,如下比如要给<app-about></app-about>添加动态样式。
import { Component } from '@angular/core';
@Component({
selector: ‘app-about’,
styleUrls: ['./about.component.scss'],
templateUrl: './about.component.html'
})
export class AboutComponent {
open = false;
}
这就需要用到host或者hostBinding,有下面3中方法:
参考:
http://angular.cn/api/core/HostBinding
https://zhuanlan.zhihu.com/p/347464587
angular 控件css_Angular5给组件本身的标签添加样式class的方法
https://stackoverflow.com/questions/35168683/hostbinding-with-a-variable-class-in-angular
1.使用@component的host属性, 注意属性的值默认为变量,如果直接使用属性值,需要加字符串单引号或者双引号,变量直接在组件里定义即可
@Component({
selector: ‘app-about’,
host: {
'[style.color]' : "'red'",
'[style.background]' : "bgColor"
'[class.myClass]' : "showMyClass"
}
styles: [`
.myClass {
color: orange;
}
`]
})
Class AboutComponent {
bgColor = "yellow";
showMyClass = true;
}
2 使用host样式,这样能加样式,但是就是加不了动态样式,但是注意最后tips,还会有用的。
@Component({
selector: ‘app-about’,
styles: [`
:host {
color: orange;
}
`]
})
3.使用hostBinding给当前组件绑定class,然后在style里定义class即可
Class AboutComponent {
@HostBinding('class.className') get className () {return showMyClass};
}
Tips:
如果在styles里定义的class加到DOM了,但是样式不起作用,不妨加:host试试,也就是定义的class从host开始找。因为我加了也遇到了class有了但是样式不起作用的问题。
参考的这个文章https://zhuanlan.zhihu.com/p/347464587
比如:
:host.myClassName