如何在全局样式表中设置角度4组件选择器的样式?

时间:2018-03-02 10:08:26

标签: angular components angular2-template

我需要在我的全局样式表中为我的组件选择器添加一些样式属性,但添加的样式不会影响浏览器中的选择器元素。 如何完成此操作以影响组件选择器元素上的样式。

我的组件文件

@Component({
  selector: 'admin-dashboardwidgets',
  templateUrl: './dashboardwidgets.component.html'
})

Mys样式表文件

admin-dashboardwidgets {
   width: 100%;
   height:500px;
   background: red;
}

提前致谢

4 个答案:

答案 0 :(得分:3)

为什么要在全局样式表中使用它?您可以直接在组件的scss文件中使用:host combinator

<强> dashboardwidgets.component.scss

:host{
   width: 100%;
   height:500px;
   background: red;
}

<强> dashboardwidgets.component.ts

@Component({
  selector: 'admin-dashboardwidgets',
  templateUrl: './dashboardwidgets.component.html',
  styleUrls: ['./dashboardwidgets.component.scss']
})

https://angular.io/guide/component-styles#host

  

使用:host伪类选择器来定位承载组件的元素中的样式(而不是在组件模板中定位元素)。

答案 1 :(得分:2)

通过使用类选择器 - 您可以实现此目的。

import { Component, ViewEncapsulation } from '@angular/core';

 @Component({
   selector: '.admin-dashboardwidgets', // class selector
   templateUrl: './dashboardwidgets.component.html',
   styles: [` .admin-dashboardwidgets{
     width: 100%;
     height:200px;
     background: red;
     }`],
     encapsulation: ViewEncapsulation.None
 })

<div class="admin-dashboardwidgets"></div> // HTML

检查live link

答案 2 :(得分:1)

您需要为组件提供styleUrl。它会是这样的:

@Component({
  selector: 'admin-dashboardwidgets',
  templateUrl: './dashboardwidgets.component.html',
  styleUrls: ['./dashboardwidgets.component.scss']
})

答案 3 :(得分:0)

如果要为所有组件应用全局样式,则必须创建样式表文件并将其添加到.angular-cli.json中的样式数组中。

"styles": [
   "globalStyles.scss"
]

如果您只想要一个组件的样式,可以将它添加到组件styleUrls数组中:

@Component({
  selector: 'admin-dashboardwidgets',
  templateUrl: './dashboardwidgets.component.html',
  styleUrls: ['./dashboardwidgets.component.scss']
})