angular項(xiàng)目中,我們都知道可以用?
[class.className]="variable"?
或者?
[style.styleName]="styleValue"?
這2種方法給組件中的元素添加動(dòng)態(tài)樣式。
但是如果給當(dāng)前組件的標(biāo)簽添加動(dòng)態(tài)樣式呢,如下比如要給<app-about></app-about>添加動(dòng)態(tài)樣式。
import?{?Component?}?from?'@angular/core';
@Component({
? ? selector: ‘a(chǎn)pp-about’,
????styleUrls:?['./about.component.scss'],
????templateUrl:?'./about.component.html'
})
export?class?AboutComponent?{
????open?=?false;
}
這就需要用到host或者h(yuǎn)ostBinding,有下面3中方法:
參考:
http://angular.cn/api/core/HostBinding
https://zhuanlan.zhihu.com/p/347464587
angular 控件css_Angular5給組件本身的標(biāo)簽添加樣式class的方法
https://stackoverflow.com/questions/35168683/hostbinding-with-a-variable-class-in-angular
1.使用@component的host屬性, 注意屬性的值默認(rèn)為變量,如果直接使用屬性值,需要加字符串單引號或者雙引號,變量直接在組件里定義即可
@Component({
? ? selector: ‘a(chǎn)pp-about’,
? ? host: {
? ? ? ? ? ? '[style.color]' : "'red'",
? ? ? ? ? ? '[style.background]' : "bgColor"
? ? ? ? ? ? '[class.myClass]' : "showMyClass"
? ? }
? ? styles: [`?
? ? ? ? .myClass {
? ? ? ? ? ? ? ? ? ? color: orange;
????????????}
????`]
})
Class AboutComponent {
? ??????bgColor = "yellow";
? ??????showMyClass = true;
}
2 使用host樣式,這樣能加樣式,但是就是加不了動(dòng)態(tài)樣式,但是注意最后tips,還會有用的。
@Component({
? ? selector: ‘a(chǎn)pp-about’,
? ? styles: [`?
? ? ? ? :host {
????????????????color: orange;
????????????}
????`]
})
3.使用hostBinding給當(dāng)前組件綁定class,然后在style里定義class即可
Class AboutComponent {
? ??????@HostBinding('class.className')? get? className () {return showMyClass};
}
Tips:
如果在styles里定義的class加到DOM了,但是樣式不起作用,不妨加:host試試,也就是定義的class從host開始找。因?yàn)槲壹恿艘灿龅搅薱lass有了但是樣式不起作用的問題。
參考的這個(gè)文章https://zhuanlan.zhihu.com/p/347464587
比如:
:host.myClassName