1

I have the following components in my application:

  1. NavbarComponent
  2. HomeComponent
  3. ClassroomComponent

I use NavbarComponent in both HomeComponent and ClassroomComponent like this:

// home.component.html 

<app-navbar></app-navbar>
..something related to HomeComponent

// classroom.component.html

<app-navbar></app-navbar>
..something related to ClassroomComponent

I want to customize navbar depending on where it is used: for example, if it's used in HomeComponent, I want it to be red, and if otherwise, then set its color to green. Is there any way I can do this?

2

2 Answers 2

1

You can try to use the :host-context selector to define the component styles based on it's ancestor.

For your example it should be working like this:

// 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;
}

More about special CSS selectors can be found here.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, it has helped! One more question. In my case, navbar has a complex structure with usage of different classes. Is there any way I can affect not only navbar itself, but also its child classes? Something like this: :host-content(home-component) { background: red; .topnav a { text-align: center; }
You could just target children like: :host-context(my-selector) .child-class { ... }. If you want to target children inside child components you should look at the ::ng-deep selector.
0

You can change your component in different ways

  1. By using Provider(injection) to access global values
  2. By using Event (publisher/subscriber methodology) procedure http://learnangular2.com/events/
  3. You can define a @Input decorator in the NavbarComponent https://github.com/ionic-team/ionic/issues/5741 or http://www.concretepage.com/angular-2/angular-2-custom-event-binding-eventemitter-example

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.