2016-07-24 40 views
1

我正在努力解決如何觸發父組件模板中的本地引用,即#rightNav從子組件模板單擊事件(click)="rightNav.open()"使用Material 2 sidenav。我想我需要使用@ViewChild註釋,但不知道如何。如何從Angular 2中的子組件事件觸發父組件中的本地引用?

子組件模板(應用條件列表):

<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>`, 

和事件的事件像

<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() 
    } 
} 
相關問題