Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to style a sibling component in Angular2?

Tags:

html

css

angular

I have a search component containing a logo, a searchbar and a routeroutlet. The execution of a search navigates to the resultlist, which is the pseudo html outlined here:

<search>
  <logo></logo>
  <searchbar></searchbar>
  <result-list></result-list>
</search>

I like to style logo and searchbar differently on the results page so I tried to select the logo with :host >>> logo and the /deep/ alternative from the result-listcomponent. That doesn't work. Is there a way to select siblings?

Here a small plnkr to demonstrate the problem. http://plnkr.co/edit/Q0CLjcsftbqe0kHKrKks?p=preview Here I would like to style from resultlist the logo and the searchbarto be black.

like image 668
Matthias Baumgart Avatar asked Dec 30 '16 07:12

Matthias Baumgart


2 Answers

A Similar solution to the one from Jens Habegger using :host-context(myCssClass) and a conditional. The style needs to be added to the logo and the searchbar component.

<search>
  <logo [class.myCssClass]="isSearchResultList"></logo>
  <searchbar [class.myCssClass]="isSearchResultList"></searchbar>
  <result-list></result-list>
</search>
:host-context(.myCssClass) {
  color: black;
 }
like image 186
Matthias Baumgart Avatar answered Oct 13 '22 00:10

Matthias Baumgart


What you are attempting is basically sharing global application state isSearchResultList: boolean across multiple components.

The obvious naive solution would be to hold the state at the respective shared parent component, and set it based on the current router-outlet.

<search>
  <logo [isSearchResultList]="isSearchResultList"></logo>
  <searchbar [isSearchResultList]="isSearchResultList"></searchbar>
  <result-list></result-list>
</search>
like image 27
Jens Habegger Avatar answered Oct 12 '22 23:10

Jens Habegger