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

如何在全局样式表中设置angular 4组件选择器的样式?,angular,components,angular2-template,Angular,Components,Angular2 Template,我需要向全局样式表中的组件选择器添加一些样式特性,但添加的样式不会影响浏览器中的选择器元素。 如何完成此操作以影响零部件选择器元素上的样式 我的组件文件 @Component({ selector: 'admin-dashboardwidgets', templateUrl: './dashboardwidgets.component.html' }) Mys样式表文件 admin-dashboardwidgets { width: 100%; height:500px;

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

我的组件文件

@Component({
  selector: 'admin-dashboardwidgets',
  templateUrl: './dashboardwidgets.component.html'
})
Mys样式表文件

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

提前感谢

您需要提供组件的样式URL。是这样的:

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

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

dashboardwidgets.component.scss

dashboardwidgets.component.ts

使用:host伪类选择器以承载组件的元素中的样式为目标,而不是以组件模板中的元素为目标


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

如果只需要一个组件的样式,可以将其添加到组件样式URL数组中:

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

通过使用类选择器-您可以实现这一点

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
检查

"styles": [
   "globalStyles.scss"
]
@Component({
  selector: 'admin-dashboardwidgets',
  templateUrl: './dashboardwidgets.component.html',
  styleUrls: ['./dashboardwidgets.component.scss']
})
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