首頁  >  文章  >  web前端  >  怎樣使用Angular5為元件標籤添加樣式class

怎樣使用Angular5為元件標籤添加樣式class

php中世界最好的语言
php中世界最好的语言原創
2018-05-26 15:35:561591瀏覽

這次帶給大家怎麼使用Angular5為元件標籤加入樣式class,使用Angular5為元件標籤加入樣式class的注意事項有哪些,以下就是實戰案例,一起來看一下。

在Angular 5為元件本身的標籤新增樣式有兩種方法:

方式一:使用@Component的host屬性

@Component({
 selector : 'myComponent',
 host : {
  '[style.color]' : "'red'", 
  '[style.background-color]' : 'backgroundColor'
 }
})
class MyComponent {
 backgroundColor: string;
 constructor() {
  this.backgroundColor = 'blue';
 }
}

在host配置裡新增屬性,等於標籤上綁定屬性的用法一樣。

設定style:

  1. '[style.color]': "'red'":注意red值雙引號裡還有一個單引號。

  2. '[style.background-color]':'backgroundColor':這裡是引用了元件裡的變數backgroudColor。

這種方式的好處是可以在樣式上使用元件的變數。

設定class:

@Component({
 selector : 'myComponent',
 host : {
  '[class.myclass]' : 'showMyClass'
 }
})
class MyComponent {
 showMyClass = false;
 constructor() {
 }

 toggleMyClass() {
  this.showMyClass = !this.showMyClass;
 }
}

方式二:在樣式裡使用:host選擇器

@Component({
 selector : 'myComponent',
 styles : [`
  :host {
   color: red;
   background-color: blue;
  }
 `]
})
class MyComponent {}

相信看了本文案例你已經掌握了方法,更多精彩請關注php中文網其它相關文章!

推薦閱讀:

怎麼正確使用vuex專案結構目錄與設定

怎麼處理vue-router懶載入時候第一次載入資源過多導致速度緩慢

以上是怎樣使用Angular5為元件標籤添加樣式class的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn