子组件EventEmitter无法正常工作

时间:2016-08-10 20:02:50

标签: angular typescript angular2-directives angular2-services

我有CreateProjectComponent,它是子组件,我需要在单击closeModal时关闭Parent中的div

模板(html):

<div (click)="closeModal(true)"></div>

component.ts

@Component({
    moduleId: module.id,
    selector: "th-create-project",
    templateUrl: "create-project.component.html",
    styleUrls: ["create-project.scss"],
    directives: [
        ThAutocomplete,
        MD_CARD_DIRECTIVES,
        MD_BUTTON_DIRECTIVES,
    ],
})

export class CreateProjectComponent  {
    @Output() onVoted = new EventEmitter<boolean>();

    public closeModal(agreed: boolean) {
        console.log("vote() on CHILD")

        this.onVoted.emit(true);
    }
}

父组件

在父母组件模板中,我有:

<div *ngIf="(isNewProjectVisible === true)" (onVoted)="receivedEvent()">

在父组件ts中我有:

@Component({
    selector: "projects-component",
    templateUrl: `client/+projects/projects.component.html`,
    styleUrls: ["client/+projects/projects.scss"],
    directives: [ProjectListComponent, SelectListComponent, CreateProjectComponent],
    providers: [ProjectService, StateService, CreateProjectService],
})
export class ProjectsComponent extends MeteorComponent implements OnInit {

    public receivedEvent() {  //This method isn't being triggered!!!
        this.isNewProjectVisible = false;
        console.log("receivedEvent() on PARENT")

    }

1 个答案:

答案 0 :(得分:1)

而不是div,您需要指定要使用的组件的选择器:

<th-create-project *ngIf="isNewProjectVisible" (onVoted)="receivedEvent()">
</th-create-project>

注意,如果使用div,Angular将不会仅仅因为您正在使用其输出属性之一而自动实例化CreateProjectComponent的实例 - 即,仅仅因为(onVoted)在父模板中。 Angular也不会自动实例化CreateProjectComponent的实例,因为它列在directives数组中。您必须使用选择器在模板中指定它,如上所示,以获取实例。