Reputation: 1946
Is there a way to seal my Angular component off from the global style sheet? I don't want the styles in the global style sheet to take effect inside my component.
I have tried this
.reset {
all: initial;
* {
all: unset;
}
}
but is there not a different way?
Upvotes: 6
Views: 9899
Reputation: 415
It should be possible because Angular provides a hierarchy for the stylesheets where the global style sheet is on top of everything.
However it is possible to exclude your component from this hierarchy by adding encapsulation: ViewEncapsulation.None
to your component's metadata, inside the decorator @component
@Component({
selector: 'app-my-component',
templateUrl: './my-component.component.html',
styleUrls: ['./my-component.component.scss'],
encapsulation: ViewEncapsulation.None
})
export class myComponent {
[...]
}
But in this way you excluded everything in that component from being affected from global style sheet.
Another approach would be set you rule as !important
overriding any global rule
.reset {
all: initial !important;
* {
all: unset !important;
}
}
If I remember well you can workaround this problem even by defining a CSS id selector instead of CSS class, so it will be something like (not sure)
#reset {
all: initial !important;
* {
all: unset !important;
}
}
Upvotes: 0
Reputation: 894
By the name itself those styles are globally across all your components affected.That is the typical behavior of CSS, whenever it encounters an element, it applies all the defined css rules for that element.Anyway Angular components are view encapsulated, therefore with Angular's default view encapsulation strategy, you can override those styles in you component styles.
Upvotes: 0
Reputation: 1485
In your component decorator, add:
@Component({
selector: '..',
templateUrl: '..',
styleUrls: ['..'],
encapsulation: ViewEncapsulation.ShadowDom
})
This will create a shadow dom and will force your component to use styles only from the provided styles/styleUrls array.
If you are using angular version < v6.1.0. You can use ViewEncapsulation.Native. It's deprecated after that.
Upvotes: 10
Reputation: 922
add below code with reset class on starting of component template.
.reset {
* {
all: unset !important;
}
}
Upvotes: 0
Reputation: 1639
try this, it must work:
:host ::ng-deep .reset{
//your style
}
Upvotes: 2
Reputation: 4787
It is impossible. The only way to achieve this is to override your rules defined in your global stylesheet in your component stylesheet.
Upvotes: 0