Angular 2

时间:2016-07-14 09:07:12

标签: angular

我尝试从子组件向父组件发出一个事件,就像在此处描述的Angular手册中https://angular.io/docs/ts/latest/api/core/index/EventEmitter-class.html

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

和子组件 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;
    }
}

很快,我有国际象棋正方形,我想要突出显示我点击的那个并且不突出其他人。所以我应该遍历所有方块并将 isSelected 属性设置为false。但事件只是没有发出。我在控制台看不到任何东西。

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

2 个答案:

答案 0 :(得分:2)

将模板更改为此,并且会发生魔术:

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

您正在select()而不是SquareModel上呼叫SquareComponent。并且您没有绑定squareModel上的squareComponent ..

答案 1 :(得分:0)

我应该注意一件事。 PierreDuc 的方法有效,但现在在 square.component.ts 中,命令this.isSelected = !this.isSelected;不起作用,因为这是指组件本身,而不是广场。所以现在我们需要将模板中的方块传递给方法:

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

和这样的特质:

select(square: Square) {
    square.isSelected = !square.isSelected;
}