是否可以在Angular 2中设置不同的相同组件?

时间:2016-08-23 14:27:12

标签: javascript angular

我有一个通用组件,我想在整个应用程序中重复使用。问题是我想为网站的各个部分设置不同的样式。这可能吗?

我猜这是传递styleUrl路径的方法,但这看起来非常混乱,我希望有更好的选择。

我也试过了,但它没有用:指定组件时,在类中添加类似的东西

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

然后将基于customStyle1的样式添加到通用组件的样式表中,但它似乎没有了解样式。

2 个答案:

答案 0 :(得分:7)

您可以在样式中使用template<class... T> void f(void(*)(T..., char)) {} 根据您使用的某个类来定位:host-context

详细了解here!!

<强> test.css

component

<强> app.component

:host-context(.theme-green) h3 {
   background-color: green;
}

:host-context(.theme-red) h3 {
   background-color: red;
}

<强> test.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(){}
}

以下是Plunker!!

希望这会有所帮助!!

答案 1 :(得分:3)

您可以将:host(...)选择器与@HostBinding()结合使用,如:

@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"
}

然后切换样式

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

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

<my-comp></my-comp>

您也可以像在问题中那样从外部申请课程,然后使用{/ 1}}选择器

:host(...)

然后你不需要这部分

:host(.customStyle1) {

但如果您想将样式与组件的其他配置设置相结合,这种方式可能会有所帮助。

相关问题