2016-05-14 131 views
1

我創建一個angular2應用程序。我有一個子組件(MountainListComponent),它由包含在父組件中的其他組件組成(但這不重要)。 在子組件中我有一個山脈列表(<my-mountain class="col-md-4" *ngFor="#mountain of mountains" [mountain]="mountain" (click)="onChange()"></my-mountain>),當我點擊山峯時,我想將一個布爾變量(hidelist)傳遞給父組件。輸入和輸出在angular2

這兩個組件的代碼如下。 我已經刪除了樣板代碼。

父組件:

import {Component, Input} from "angular2/core"; 
import {MountainListComponent} from "./mountain-list.component"; 

@Component({ 
    selector: 'my-mountains', 
    template: `hidelist value: {{hidelist}} 
     <div class="row spacing" (childChanged)="hidelist=$event" *ngIf="!hidelist"> 
      <my-mountain-list></my-mountain-list> 
     </div> 
    ` 
}) 

export class MountainsComponent { 
    hidelist = false; 
} 

子組件:

import {Component, Output, EventEmitter} from "angular2/core"; 
import {MountainComponent} from "./mountain.component"; 
import {Mountain} from "./mountain"; 

@Component({ 
    selector: 'my-mountain-list', 
    template: ` 
     <section class="col-md-12"> 
      <my-mountain class="col-md-4" *ngFor="#mountain of mountains" [mountain]="mountain" (click)="onChange()"></my-mountain>  
     </section> 
    `, 
    directives: [MountainComponent], 
    outputs: ['childChanged'] 
}) 

export class MountainListComponent implements OnInit { 
    childChanged = new EventEmitter<boolean>(); 

    onChange() { 
     var hidelist: boolean; 
     hidelist = true; 
     this.childChanged.emit(hidelist); 
    } 
} 

的問題是,hidelist變量值始終爲false

回答

0

添加模板變量#mountain比你可以參考該組件在表達式中:

<my-mountain class="col-md-4" 
    *ngFor="#mountain of mountains" [mountain]="mountain" 
    #mountain 
    (click)="onChange(mountain.hidelist)"></my-mountain> 
0

將自定義事件綁定從div移至<my-mountain-list>組件,如下所示。

<my-mountain-list (childChanged)="hidelist=$event"></my-mountain-list>

我已經更新父組件: -

import {Component, Input} from "angular2/core"; 
import {MountainListComponent} from "./mountain-list.component"; 

@Component({ 
    selector: 'my-mountains', 
    template: `hidelist value: {{hidelist}} 
     <div class="row spacing" *ngIf="!hidelist"> 
      <my-mountain-list (childChanged)="hidelist=$event"></my-mountain-list> 
     </div> 
    ` 
}) 

export class MountainsComponent { 
    hidelist = false; 
}