James May James May - 4 months ago 24
AngularJS Question

EventEmitter trouble in Angular 2

I try to emit an event from child component to parent, just like in Angular's manual described here https://angular.io/docs/ts/latest/api/core/index/EventEmitter-class.html

My app.component.ts:

import { Component, Input } from '@angular/core';
import { SquareService } from './services/square.service';
import { Square } from './models/square';

@Component({
selector: 'squares',
template: `
<square *ngFor="let square of squares"
(click)="square.select()"
(notify)="onNotify($event)"></square>
`,
providers: [SquareService],
directives: [Square]
})
export class AppComponent {
squares: Square[];

constructor(private squareService: SquareService) { }

// UPD added
processSquare(row: number, col: number) {
this.col = col;
this.row = row;
this.coords = this.cols[col] + (8 - row).toString();

return this;
}

// Nevermind
ngOnInit():any {
this.squares = this.squareService.genSquares();
}

// Cant get here =(
onNotify(event):void {
console.log(event);
}
}


and child component square.component.ts:

import {Component, Input, Output, EventEmitter} from '@angular/core';

@Component({
selector: 'square',
template: `
<span>nevermind</span>
`,
directives: [Piece],
})
export class Square {
@Input() square: Square;
@Output() notify: EventEmitter<any> = new EventEmitter();

public isSelected = false;

select() {
this.notify.emit(null);
this.isSelected = !this.isSelected;
}
}


Shortly, I have the chess squares, I wanna highlight the one I clicked on and unhighlight the others. So I should iterate through all squares and set isSelected property to false. But the event just does not emit. I see nothing in console.

UPD square.service.ts:

import {Injectable} from '@angular/core';
import {Square} from "../models/square";

@Injectable()
export class SquareService {
/**
* Generates the squares for the board
* @returns {Array}
*/
genSquares() {
let ret = [];

for (let row = 0; row < 8; row++) {
for (let col = 0; col < 8; col++) {
let square = (new Square).processSquare(row, col);
ret.push(square);
}
}

return ret;
}
}

Answer

Change your template to this, and magic will happen:

<square *ngFor="let square of squares"
    (click)="squareComp.select()"
    (notify)="onNotify($event)"
    [square]="square"
    #squareComp>
</square>

You are calling select() on a SquareModel and not on the SquareComponent. And you did not bind the squareModel on your squareComponent..

Comments