Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extend/Override style of reusable angular2 component

Tags:

angular

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.

like image 760
patrickkeller Avatar asked Jun 01 '16 12:06

patrickkeller


People also ask

How to override style in Angular component?

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.

How to override CSS property in Angular?

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.

Can we extend component in Angular?

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.


1 Answers

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/

like image 55
Mohammed Safeer Avatar answered Sep 24 '22 00:09

Mohammed Safeer