输入和输出为angular2

时间:2016-05-14 18:01:51

标签: angular

我正在创建一个angular2应用程序。我有一个子组件(MountainListComponent),它由包含在父组件中的其他组件组成(但这并不重要)。 在子组件中,我有一个山的列表(<my-mountain class="col-md-4" *ngFor="#mountain of mountains" [mountain]="mountain" (click)="onChange()"></my-mountain>),当我点击一个山时,我想将一个布尔变量(hidelist)传递给父组件。

这两个组件的代码如下。 我删除了样板代码。

父组件:

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变量值始终为假

2 个答案:

答案 0 :(得分:0)

添加模板变量#mountain,而不是在事件表达式中引用该组件:

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

答案 1 :(得分: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;
}