angular組件當(dāng)前組件host動(dòng)態(tài)添加樣式

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

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Angular 2+ (Now 5.0) 應(yīng)用程序使用的是常規(guī)CSS樣式,意思就是說CSS標(biāo)準(zhǔn)中的所有東西都可以直...
    山哥Samuel閱讀 3,703評論 0 0
  • Theming your custom components 主體化自定義的組件 In order to styl...
    王義杰閱讀 974評論 0 1
  • 在前面的問題匯總的第四個(gè)里,介紹過angular2的組件投影,也就是我們在使用組件的時(shí)候,父組件可以用屬性...
    avery1閱讀 1,565評論 0 0
  • 我是黑夜里大雨紛飛的人啊 1 “又到一年六月,有人笑有人哭,有人歡樂有人憂愁,有人驚喜有人失落,有的覺得收獲滿滿有...
    陌忘宇閱讀 8,899評論 28 54
  • 信任包括信任自己和信任他人 很多時(shí)候,很多事情,失敗、遺憾、錯(cuò)過,源于不自信,不信任他人 覺得自己做不成,別人做不...
    吳氵晃閱讀 6,394評論 4 8

友情鏈接更多精彩內(nèi)容