[英]In Angular 7, how do I access the component that emitted an event?
Let's say I have a component with a custom event: 假设我有一个带有自定义事件的组件:
child.component.html child.component.html
<button (click)="buttonClicked()">Test</button>
child.component.ts child.component.ts
@Component({
selector: 'my-child',
templateUrl: './child.component.html'
})
export class ChildComponent {
@Output() myEvent = new EventEmitter();
public buttonClicked() {
this.myEvent.emit();
}
}
Then I have another component that contains multiple instances of the first component. 然后,我有另一个组件,其中包含第一个组件的多个实例。
parent.component.html parent.component.html
<my-child id="my-child-component-1" (myEvent)="myEventOccured()" />
<my-child id="my-child-component-2" (myEvent)="myEventOccured()" />
parent.component.ts 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.
}
}
In the function that handles the custom event of the child components (myEventOccured()), I want to access the component that emitted the event. 在处理子组件的自定义事件的函数(myEventOccured())中,我要访问发出该事件的组件。 How do I do that?
我怎么做?
I'm thinking maybe I should send the emitting component as an argument to the function handling the event (myEventOccured()), but I don't know how. 我在想也许应该将发射组件作为参数发送给处理事件的函数(myEventOccured()),但我不知道如何。
you can pass a value when emitting, and collect it back in parent using $event
您可以在发出时传递值,并使用
$event
将其收集回父$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);
}
}
However, I'm not sure it is a good practice to pass the entire component. 但是,我不确定传递整个组件是否是一个好习惯。 You may consider emitting only what you really need in the parent.
您可以考虑只释放父母真正需要的东西。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.