Is it possible to create the same component in Angular 2?

I have a common component that I want to reuse throughout the application. The problem is that I want to style it differently for different parts of the site. Is it possible?

I suppose there is a way to pass the path for styleUrl, but it seems really dirty, and I hope there will be a better alternative.

I also tried this, but it did not work: when specifying the component, add something like this to the class

<generic-component class="customStyle1"></generic-component> 

and then we added a customStyle1-based style to the stylesheet with a standard component, but it didn't seem to fit the style.

+5
source share
2 answers

You can use :host-context style :host-context for the theme of your component based on some class applied where it is 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!

+4
source

You can use the :host(...) selector in combination with @HostBinding() as follows:

 @Component({ selector: 'my-comp', styles: ` :host([type-default]) { background-color: red; } :host([type-header]) { background-color: blue; } :host([type-main]) { background-color: green; } ` }) export class MyComponent { @Input() @HostBinding('component-type') componentType:String="type-default" } 

and then switch the style like

 <header> <my-comp componentType="type-header"></my-comp> </header> <main> <my-comp componentType="type-main"></my-comp> </main> <my-comp></my-comp> 

You can also apply the class outside, as in your question, and then use the selector :host(...) , for example

 :host(.customStyle1) { 

Then you do not need this part

  @Input() @HostBinding('component-type') componentType:String="type-default" 

but this method can be useful if you want to combine the style with other configuration settings for the component.

+3
source

All Articles