在Angular 7中,如何访问发出事件的组件?

时间:2019-08-16 08:25:39

标签: angular events

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

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()),但我不知道如何。

1 个答案:

答案 0 :(得分: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);
    }
}

但是,我不确定传递整个组件是否是一个好习惯。您可以考虑只释放父母真正需要的东西。