簡體   English   中英

在Angular 7中,如何訪問發出事件的組件?

[英]In Angular 7, how do I access the component that emitted an event?

假設我有一個帶有自定義事件的組件:

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

您可以在發出時傳遞值,並使用$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);
    }
}

但是,我不確定傳遞整個組件是否是一個好習慣。 您可以考慮只釋放父母真正需要的東西。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM