James May James May - 1 year ago 112
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';

selector: 'squares',
template: `
<square *ngFor="let square of squares"
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 {

and child component square.component.ts:

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

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

public isSelected = false;

select() {
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";

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

return ret;

Answer Source

Change your template to this, and magic will happen:

<square *ngFor="let square of squares"

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download