2016-07-24 9 views
1

子コンポーネントのテンプレートクリックイベント(click)="rightNav.open()"から#rightNavを使用して、親コンポーネントテンプレートのローカル参照をMaterial 2 sidenavを使用してトリガーする方法を試しています。 @ViewChild注釈を使用する必要があるとは思いますが、その方法はわかりません。子コンポーネントイベントから親コンポーネントのローカル参照を角度2でトリガする方法はありますか?

子コンポーネントテンプレート(APP-条件リスト):

<div *ngFor="let condition of conditions" [class.selected]="condition === selectedCondition" 
      (click)="rightNav.open()"></div> 

親コンポーネントテンプレート(条件コンポーネント):子コンポーネントは、親コンポーネント内にネストされ

import { Component} from '@angular/core'; 
import { ConditionsListComponent } from './listComponent/conditions-list.component'; 


@Component({ 
    moduleId: module.id, 
    selector: 'app-conditions', 
    template: ` 
      <md-sidenav #rightNav align="end" mode="side"> 
      "Condition details will open here on click event" 
      </md-sidenav> 
      <app-conditions-list></app-conditions-list>`, 
    styleUrls: ['./conditions.component.css'], 
    directives: [ 
     ConditionsListComponent, 
    ] 
}) 

export class ConditionsComponent { 
    title = "Conditions Manager" 
} 

テンプレート。 ありがとう!

+0

それは ''と 'は'どのように関連しているかは明らかではありません。 「親コンポーネント」とはどういう意味ですか? –

+0

ありがとう@GünterZöchbauer。無関係なコードを削除するコードを整理しました。親コンポーネントは、#rightNav参照がある場所です。 – odenman250

+0

コードを追加してください。私にはあなたが達成しようとしていることはまだ完全には不明です。 –

答えて

1

あなたが好き要素兄弟を参照するには、テンプレート変数を使用することができ、それ

export class ConditionsListComponent { 
    @Output() navOpen:EventEmitter = new EventEmitter(); 
} 

から子コンポーネントに出力を追加し、イベントに耳を傾けることができます。

<div #rightNav align="end" mode="side" (close)="close($event)"</div> 
<app-conditions-list (navOpen)="rightNav.open()"></app-conditions-list>`, 

とイベントイベントlike

<div *ngFor="let condition of conditions" [class.selected]="condition === selectedCondition" 
     (click)="navOpen.next(null)"></div> 
1

イベントを子供から親にバブリングする必要があります:

The child : 

export class ConditionsListComponent { 
    @Output('myEvent') myEvent = new EventEmitter(); 

    private bubbleUp($event:Event){ 

    myEvent.emit($event) 
    } 
} 

それの見解:

<div *ngFor="let condition of conditions" [class.selected]="condition === selectedCondition" 
     (click)="bubbleUp($event)"></div> 

と親は:私にとって

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

@Component({ 
moduleId: module.id, 
selector: 'app-conditions', 
template: ` 
     <div #rightNav align="end" mode="side" (close)="close($event)"</div> 
     <app-conditions-list (myEvent)='gotTheEvent($event)' ></app-conditions-list>`, 
styleUrls: ['./conditions.component.css'], 
providers: [], 
directives: [ 
    ConditionsListComponent, 
] 
}) 

export class ConditionsComponent { 
    title = "Conditions Manager"; 

    gotTheEvent($event){ 

    console.log('I got this event from my child',$event); 

    //you can do whatever you want : 

    rightNav.open() 
    } 
} 
関連する問題