2016-12-30 9 views
4

ロゴ、検索バー、ルーターアウトレットを含む検索コンポーネントがあります。検索の実行は、ここで概説する擬似htmlですresultlist、に移動:Angular2で兄弟コンポーネントのスタイルを設定するにはどうすればよいですか?

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

私は結果ページに異なったロゴと検索バーのスタイルを設定したいので、私は:host >>> logoでロゴを選択しようとしましたが、 result-listの代替品である/deep/の代替品です。それは動作しません。兄弟を選ぶ方法はありますか?

ここで問題を示す小さなplnkr。 http://plnkr.co/edit/Q0CLjcsftbqe0kHKrKks?p=previewここではresultlistからlogosearchbarを黒色にしたいと思います。

+0

DEP経由で任意のクラスを適用することができます36527605/how-to-style-child-components-from-parent-components-css-file – micronyks

+0

私は親からのものであり、兄弟からではないその投稿を読んでいます。 –

+0

あなたはお尻を作りたいですか? – micronyks

答えて

1

基本的には、複数のコンポーネントにわたってグローバルアプリケーション状態isSearchResultList: booleanを共有しようとしています。

明らかに単純な解決法は、それぞれの共有親コンポーネントに状態を保持し、現在のルータ - アウトレットに基づいて設定することです。

<search> 
    <logo [isSearchResultList]="isSearchResultList"></logo> 
    <searchbar [isSearchResultList]="isSearchResultList"></searchbar> 
    <result-list></result-list> 
</search> 
+0

私はそこに州を入れないことを望んだ。下の同様の解決策。 –

+0

私はそれに関連することができます、私は別のアプローチにも興味があるでしょう。 –

0
:host-context(myCssClass)

及び条件を使用してJens Habeggerから1と同様に溶液。スタイルはlogosearchbarコンポーネントに追加する必要があります。

<search> 
    <logo [class.myCssClass]="isSearchResultList"></logo> 
    <searchbar [class.myCssClass]="isSearchResultList"></searchbar> 
    <result-list></result-list> 
</search> 
:host-context(.myCssClass) { 
    color: black; 
} 
0

あなたは、ダイナミックなスタイリングのためのコンポーネントとngClass間の通信のためのサービスを使用することができます。

notification.service.ts

import {Injectable, EventEmitter} from '@angular/core'; 

@Injectable() 
export class NotificationService { 
    private static _emitters: { [ID: string]: EventEmitter<any> } = {}; 

    static get(ID: string): EventEmitter<any> { 
    if (!this._emitters[ID]) { 
     this._emitters[ID] = new EventEmitter(); 
    } 
    return this._emitters[ID]; 
    } 
} 

コンポーネントの実行がメッセージを送信する兄弟。

bar.component.ts

import { NotificationService } from 'notification.service'; 
.... 
ngOnInit() { 
     NotificationService.get('barcomponent').emit(true); 
    } 
    ngOnDestroy() { 
     NotificationService.get('barcomponent').emit(false); 
    } 
... 

は、あなたのコンポーネントから受信したメッセージに耳を傾けます。

foo.component.ts

import { NotificationService } from 'notification.service'; 
.... 
ngOnInit() { 
    NotificationService.get('barcomponent').subscribe(value => { 
     this.activateStyle = value; 
    }); 
    } 
.... 

あなたはhttp://stackoverflow.com/questions/のngClass

foo.component.html

.... 
<div [ngClass]="{'my-css-class':activateStyle}"> 
    ... 
</div> 
.... 
関連する問題