I have a generic component I want to re-use throughout my app. The problem is that I want to style it differently for various parts of the site. Is this possible?
I'm guessing there's a way to pass in a path for the styleUrl, but that seems really messy and i'm hoping there's a better alternative.
I also tried this but it didn't work: When specifying the component, add in the class, something like this
<generic-component class="customStyle1"></generic-component>
and then added styling based on customStyle1 into generic-component's stylesheet, but it didn't seem to pick up on the style.
With Angular 2+, component styles are protected and won’t bleed unto other components by default. That’s thanks to the View Encapsulation with Shadow DOM or Shadow DOM emulation.
With Angular 2+, component styles are protected and won’t bleed unto other components by default. That’s thanks to the View Encapsulation with Shadow DOM or Shadow DOM emulation. There are still ways however to play around and have a component’s style interact with it’s surrounding with :host, :host-context and /deep/ (now ::ng-deep ).
For every Angular component you write, you may define not only an HTML template, but also the CSS styles that go with that template, specifying any selectors, rules, and media queries that you need. One way to do this is to set the styles property in the component metadata. The styles property takes an array of strings that contain CSS code.
And I want those 3 components to share the same styles. Angular usually has a style file that allows you to apply classes globally in your application. You can create a class there and apply it to your components, and that you can do it in two ways, using host property, and using HostBinding decorator.
You may use :host-context
in the style to theme your component
based upon some class applied where it is being used.
Read more about it here!!
test.css
:host-context(.theme-green) h3 {
background-color: green;
}
:host-context(.theme-red) h3 {
background-color: red;
}
app.component
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
template: `
<h3 class="title">Basic Angular 2</h3>
<my-test class="theme-green" ></my-test>
<my-test class='theme-red' ></my-test>
`
})
export class AppComponent {
constructor(){}
}
test.component
@Component({
selector: 'my-test',
template: `<h3>Test Component</h3>
`,
styleUrls : ['./app/test.css']
})
export class TestComponent {
constructor(){}
}
Here is the Plunker!!
Hope this helps!!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With