1
votes

I'm creating an angular2 application. I have a child component (MountainListComponent) which is made up of other components (but that's not important) that is included into a parent component. In the child component I have a list of mountains (<my-mountain class="col-md-4" *ngFor="#mountain of mountains" [mountain]="mountain" (click)="onChange()"></my-mountain>), when I click on a mountain I'd like to pass a boolean variable (hidelist) to the parent component.

The code of these 2 components are below. I've removed boilerplate code.

Parent component:

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;
}

Child component:

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);
    }
}

The problem is that hidelist variable value is always false

2

2 Answers

0
votes

Add a template variable #mountain than you can refer to that component in the event expression:

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

Move the custom event binding from div to <my-mountain-list> component like the below.

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

I have updated parent component :-

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;
}