0

I need to add some style properties to my component selector in my global style sheet, but the added style doesn't affect the selector element in the browser. how to accomplish this to affect the style on the component selector element.

my component file

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

Mys stylesheet file

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

Thanks in advance

Manush
  • 1,852
  • 7
  • 26
  • 39

4 Answers4

4

Why do you want to use it in your global style sheet? You can use the :host combinator in your component's scss file directly

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

Use the :host pseudo-class selector to target styles in the element that hosts the component (as opposed to targeting elements inside the component's template).

Pat Migliaccio
  • 1,031
  • 13
  • 24
David
  • 33,444
  • 11
  • 80
  • 118
  • I guess it has something to do with the alternative of ng-deep like in [this answer](https://stackoverflow.com/a/53843161/7099900) , so using this combinator is not really an option. – ytan11 May 19 '22 at 02:59
2

By using class selector - you can achieve this.

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

Check the live link

Prasanth S
  • 525
  • 5
  • 19
1

You need to provide a styleUrl to the component. It would be like this:

@Component({
  selector: 'admin-dashboardwidgets',
  templateUrl: './dashboardwidgets.component.html',
  styleUrls: ['./dashboardwidgets.component.scss']
})
Boanta Ionut
  • 402
  • 8
  • 24
0

If you want a global style applied for all components you have to create a stylesheet file and add it to the styles array in .angular-cli.json.

"styles": [
   "globalStyles.scss"
]

If you only want the style for one component you can add it to the components styleUrls array:

@Component({
  selector: 'admin-dashboardwidgets',
  templateUrl: './dashboardwidgets.component.html',
  styleUrls: ['./dashboardwidgets.component.scss']
})
ochs.tobi
  • 3,214
  • 7
  • 31
  • 52