2017-10-20 3 views
0

次の状況をAngularで行うには少し問題があります。Javascript Angular 4 eventEmitterを使用していくつかのコンポーネントレイヤーを作成

私は角度4を使用していますが、これが状況です。

app.component.htmlには、クラスを追加することで色を変更できるラッパーdivが含まれています。

私の問題は、コンポーネントのレイヤーが違うことです。

私はapp.component.htmlでクラスを変更したい場合たとえば、それはこの必要があります:

import { Component } from '@angular/core'; 

@Component({ 
    selector: 'app-root', 
    templateUrl: './app.component.html', 
    styleUrls: ['./app.component.scss'] 
}) 
export class AppComponent { 
    title = 'app'; 
    myClass = ''; 

    handleEvent(value) { 
    console.log(value); 
    myClass = value; 
    } 
} 

とapp.componentで:

app.component - root 

button-wrapper.component - holds the button 

button.component - message comes from there. 

を通常、私はこれを行うことができますこれを持っているの.html:

<div [ngClass]="myClass"> 

    <app-button (outputEvent)="handleEvent($event)"></app-button> 

</div> 

をしかし、私の問題は、そのアプリボタンコンポーネントであることは私がボタンラッパーコンポーネントの内部にありますtは次のようになります。

<div [ngClass]="myClass"> 

    <button-wrapper></div> 

</div> 

だからここで私はこれを入れてしまうでしょう:

(outputEvent)="handleEvent($event)" 

は、どのように私はこの問題のラウンドに行くことができますか?

+0

'ボタンwrapper'であります'AppComponent'の中に? –

+1

複数の「レイヤー」の間で親子通信を使用するには、各レイヤーが親または子レイヤーに入出力する必要があります。または、ここで説明するように、「共有サービス」を使用して親/子ではないレイヤー間で通信することができます:https://angular.io/guide/component-interaction#parent-and-children-communicate-via-a-service –

答えて

2

することはでき連鎖イベント限り、彼らの直接の子:

button.component.ts(セレクター:アプリボタン)

startChainEvent() { 
    this.outputEvent.emit('className'); 
} 

ボタン-wrapper.component.html

<app-button (outputEvent)="handleEvent($event)"></app-button> 

button-wrapper.component.ts(セレクタ:アプリボタンラッパー)

handleEvent(e) { 
    this.outputEvent.emit(e); 
} 

app.component.html

<app-button-wrapper (outputEvent)="handleEvent($event)"></app-button-wrapper> 

app.component.ts

handleEvent(e) { 
    myClass = e; 
} 
関連する問題