Assuming we want to use a component from some library in angular2 (example from material2). The component annotation looks like this:
@Component({ moduleId: module.id, selector: 'md-input', templateUrl: 'input.html', styleUrls: ['input.css'], providers: [MD_INPUT_CONTROL_VALUE_ACCESSOR], host: {'(click)' : 'focus()'} })
This component ships with a "default" stylesheet, the "input.css". If we use this component in our app we likely want to override/extend some of the style, without copying and manipulating the component itself. How to do this?
Possible Solution 1: Set the Encapsulation to "ViewEncapsulation.None":
This is not really a solution, just a workaround.
Possible Solution 2: Use "::shadow" or "/deep/" in CSS:
Works also, but its deprecated according to WebComponent spec.
Possible Solution 3: Use global CSS and override the component CSS:
Works also, but it violates the shadow DOM concept.
Possible Solution 4: Override directly in the template of parent component:
Example:
<my-cmp [font-size]="100"></my-cmp>
Is not really suitable if we do a lot of overriding.
Possible Solution 5: Override or extend the "@Component" definition with an additional stylesheet somehow:
This seems to be the only correct solution (at least for me). But i have no idea how to do this...
Any advice on this? Maybe i got something wrong... Thanks.
By default, Angular uses the emulated encapsulation strategy to make the component styles encapsulated. This means that if we want to override a component style from our parent, we need to use the ::ng-deep selector.
Next, you need to define your CSS selector which is simply the one that you have found prepended with a sort of context, namely an element, attribute, class or id. Finally, using the tailored selector ️you can override a set of properties.
Typescript and Angular give you a way to handle this encapsulation. Inherited components! Using class inheritance in TypeScript, you can declare a base component that contains common UI functionality and use it to extend any standard component you'd like.
In Angular 4, We can override the style with the ::ng-deep
pseudo-class selector from the inherited class style sheet.
:host ::ng-deep element { //your style here }
For more information refer http://blog.angular-university.io/angular-ngclass-ngstyle/
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