子组件的@Output不会在Angular 7中触发EventEmitter

时间:2019-04-25 08:12:36

标签: angular

我希望子组件将一些数据发送到父组件。子部分按预期执行,但是父代码不响应,并且没有错误。所以,如果有什么想法...

子HTML

<button  (click)="sendDataToParent()">  CLICK ME !  </button>

儿童TS

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

@Component({
  selector: 'app-hero-detail',
  templateUrl: './hero-detail.component.html',
  styleUrls: ['./hero-detail.component.css']
})
export class HeroDetailComponent implements OnInit {

  @Input() hero : Hero;   
  @Output() sendDataHeroEvent: EventEmitter<Hero> = new EventEmitter<Hero>();

  constructor() { }
  ngOnInit() { }

  sendDataToParent(event: any){
    let hero2: Hero; hero2 = new Hero();  hero2.id = 12; hero2.name = "Narco";
    this.sendDataHeroEvent.emit(hero2);
    console.log("OK, child emits data to parent");
  }
}

父母HTMl

<h2>My Heroes</h2>
<ul class="heroes"
    (sendDataHeroEvent)="sendDataHeroEventHandler($event)">
    <li *ngFor="let hero of heroes" 
        (click)="onSelect(hero)"
        [class.selected]="hero === selectedHero"
        class="drag-box" 
        cdkDragLockAxis="y"
        cdkDrag> 
        <span class="badge">{{hero.id}}</span> {{hero.name}}
    </li>
</ul>
<app-hero-detail [hero]="selectedHero"></app-hero-detail>

父母TS

import { Component, OnInit } from '@angular/core';
...
export class HeroesComponent implements OnInit {
...
sendDataHeroEventHandler(event){
    console.log("OK, parent handler is called");
}

在Chrome的控制台日志中,我得到 “好,孩子向父母发出数据” 但我不明白 “好,调用了父处理程序”

3 个答案:

答案 0 :(得分:2)

您需要将父模板更改为

<ul class="heroes">
    <li *ngFor="let hero of heroes" 
        (click)="onSelect(hero)"
        [class.selected]="hero === selectedHero"
        class="drag-box" 
        cdkDragLockAxis="y"
        cdkDrag> 
        <span class="badge">{{hero.id}}</span> {{hero.name}}
    </li>
</ul>
<app-hero-detail [hero]="selectedHero" (sendDataHeroEvent)="sendDataHeroEventHandler($event)"></app-hero-detail>

答案 1 :(得分:2)

在子组件选择器标记中添加事件处理程序。

<app-hero-detail 
  [hero]="selectedHero"
  (sendDataHeroEvent)="sendDataHeroEventHandler($event)">
</app-hero-detail>

答案 2 :(得分:1)

您没有将output属性正确绑定到子组件。实际上,没有输出属性绑定。修改以下代码

<app-hero-detail [hero]="selectedHero"></app-hero-detail>

<app-hero-detail [hero]="selectedHero" (sendDataHeroEvent)="sendDataHeroEventHandler($event)"></app-hero-detail>

并从此处删除绑定:

<ul class="heroes"
    **(sendDataHeroEvent)="sendDataHeroEventHandler($event)"**> // Take this out
    <li *ngFor="let hero of heroes" 
        (click)="onSelect(hero)"
        [class.selected]="hero === selectedHero"
        class="drag-box" 
        cdkDragLockAxis="y"
        cdkDrag> 
        <span class="badge">{{hero.id}}</span> {{hero.name}}
    </li>
</ul>