2017-01-06 12 views
1

イベントエミッタを使用して同じレベルのの2つのコンポーネント間の通信方法はありますか?角2同じレベルのコンポーネント間の通信

添付のHTMLスニペットでコメントを参照してください。

<div class="custom-container"> 
 
    <div class="row"> 
 
    <div class="col-xs"> 
 
     <app-entity-listing (associationShown)=" TO DO " [isFromRoot]="isFromRoot"> 
 

 

 
     <!-- I am emiting a boolean value --> 
 
     </app-entity-listing> 
 
    </div> 
 

 
    <div class="col-xs-5"> 
 
     <div class="right-column-wrapper"> 
 
     <div class="main-container"> 
 
      <app-create-entity-screen-no-association [isVisible]="true"></app-create-entity-screen-no-associatio 
 

 

 
     <! -- Based on emitted value from the first component, I will be visible or not --> 
 
     </div> 
 
     </div> 
 
    </div> 
 

 
    </div> 
 
</div>

enter image description here

+2

これは、子供たちの間で通信を満たすために親コンポーネントが必要です。通信がこのように、またはサービスを通じて行われるべきかどうかは、ケースによって異なります。 – estus

答えて

0

あなたは子コンポーネント(子B)の可視性に関する情報を保持している親コンポーネント(親)を作成することができます。別の子コンポーネント(CHILD A)から、EventEmitterを使用して可視性を変更できます。画像とコードを参照してください。

enter image description here

import { Component, ViewChild, Output, EventEmitter } from '@angular/core'; 

@Component({ 
    selector: 'app-root', 
    template: ` 
    <div style='background: red; padding: 10px; margin: 10px;'> 
    <app-parent></app-parent> 
    </div> 
    `, 
}) 
export class AppComponent { 
} 

@Component({ 
    selector: 'app-child-a', 
    template: ` 
    <h3>CHILD A</h3> 
    <button (click)='changeVisibility(true)'>Show</button> 
    <button (click)='changeVisibility(false)'>Hide</button> 
    `, 
}) 
export class ChildAComponent { 

    @Output() onVisibilityChanged = new EventEmitter<boolean>(); 

    changeVisibility(visible: boolean) { 
    this.onVisibilityChanged.emit(visible); 
    } 

} 

@Component({ 
    selector: 'app-child-b', 
    template: ` 
    <h3>CHILD B</h3> 
    `, 
}) 
export class ChildBComponent { 
} 

@Component({ 
    selector: 'app-parent', 
    template: ` 
    <h3>PARENT</h3> 
    <div style='background: green; padding: 10px; margin: 10px;'> 
    <app-child-a (onVisibilityChanged)='onVisibilityChanged($event)'></app-child-a> 
    </div> 
    <div *ngIf=visible style='background: blue; padding: 10px; margin: 10px;'> 
    <app-child-b></app-child-b> 
    </div> 
    `, 
}) 
export class ParentComponent { 

    visible = false; 

    onVisibilityChanged(visible: boolean) { 
    this.visible = visible; 
    } 

} 
関連する問題