根据Angular2 / 4的使用位置自定义组件

时间:2017-09-28 23:42:34

标签: javascript angular

我的应用程序中包含以下组件:

  1. NavbarComponent
  2. HomeComponent
  3. ClassroomComponent
  4. 我在HomeComponent和ClassroomComponent中使用NavbarComponent,如下所示:

    // home.component.html 
    
    <app-navbar></app-navbar>
    ..something related to HomeComponent
    
    // classroom.component.html
    
    <app-navbar></app-navbar>
    ..something related to ClassroomComponent
    

    我想根据使用的位置自定义导航栏:例如,如果它在HomeComponent中使用,我希望它为红色,如果不是,则将其颜色设置为绿色。 我有什么方法可以做到这一点吗?

2 个答案:

答案 0 :(得分:1)

您可以尝试使用:host-context选择器根据它的祖先定义组件样式。

对于你的例子,它应该像这样工作:

// inside app-navbar css file
// where 'home-component' is the selector of your HomeComponent
:host-context(home-component) {
  background: red; // NavbarComponent is red when inside HomeComponent;
}

:host-context(classroom-component) {
  background: blue; // NavbarComponent is blue when inside ClassroomComponent;
}

有关特殊CSS选择器的更多信息,请访问here

答案 1 :(得分:0)

您可以通过不同方式更改组件

  1. 使用Provider(注入)访问全局值
  2. 使用事件(发布者/订阅者方法)程序http://learnangular2.com/events/
  3. 您可以在NavbarComponent https://github.com/ionic-team/ionic/issues/5741http://www.concretepage.com/angular-2/angular-2-custom-event-binding-eventemitter-example
  4. 中定义@Input装饰器