【问题标题】:In Angular 7, how do I access the component that emitted an event?在 Angular 7 中,如何访问发出事件的组件?
【发布时间】:2026-02-05 03:30:02
【问题描述】:

假设我有一个带有自定义事件的组件:

child.component.html

<button (click)="buttonClicked()">Test</button>

child.component.ts

@Component({
  selector: 'my-child',
  templateUrl: './child.component.html'
})
export class ChildComponent {
    @Output() myEvent = new EventEmitter();

    public buttonClicked() {
        this.myEvent.emit();
    }
}

然后我有另一个组件,其中包含第一个组件的多个实例。

parent.component.html

<my-child id="my-child-component-1" (myEvent)="myEventOccured()" />
<my-child id="my-child-component-2" (myEvent)="myEventOccured()" />

parent.component.ts

@Component({
  selector: 'my-parent',
  templateUrl: './parent.component.html'
})
export class ParentComponent {
    public myEventOccured() {
        //HERE I WANT I REFERENCE TO THE COMPONENT EMITTING THE EVENT.
    }
}

在处理子组件的自定义事件的函数(myEventOccured())中,我想访问发出事件的组件。我该怎么做?

我在想也许我应该将发射组件作为参数发送给处理事件的函数 (myEventOccured()),但我不知道如何。

【问题讨论】:

  • (myEvent)="myEventOccured($event)"emit(&lt;whatever ref you need&gt;)
  • 你能指定什么样的访问?

标签: angular events


【解决方案1】:

您可以在发射时传递一个值,并使用$event 将其收集回父级

@Component({
  selector: 'my-child',
  templateUrl: './child.component.html'
})
export class ChildComponent {
    @Output() myEvent = new EventEmitter<ChildComponent>(); // for better type checking

    public buttonClicked() {
        this.myEvent.emit(this); // emit reference to this component
    }
}
<my-child id="my-child-component-1" myEvent="myEventOccured($event)" />
@Component({
  selector: 'my-parent',
  templateUrl: './parent.component.html'
})
export class ParentComponent {
    public myEventOccured(child: ChildComponent) {
        console.log(child);
    }
}

但是,我不确定传递整个组件是否是一个好习惯。您可以考虑仅在父级中发出您真正需要的内容。

【讨论】: