簡體   English   中英

如何在角度4中發射事件發射器?

[英]How to emit event emitter in angular 4?

有兩個組件List和Modal:

他們沒有子女與父母的關系。

問題是,當您單擊新按鈕然后openModal()方法時,將彈出窗口打開。 我設置this.isOpenModal = true;

  1. 列出組件openModal()的邏輯部分:

     public isOpenModal: boolean = false; public openModal(id: string): void { if (!this.isOpenModal) { this.isOpenModal = true; const data = {id: id}; this.modalModel.add(AudienceModel.ENTITY_NAME, data); } } 

在模態組件中,我有close()方法:

isModalOpen: boolean;

public close(index: number): void {
    this.isModalOpen = false;
    this.audienceModel.isModalOpened = this.isModalOpen;
    for (let i = 0; i < this.modalsArray.length; i++) {
        if (this.modalsArray[index].modalStyle.zIndex <= this.modalsArray[i].modalStyle.zIndex) {
            this.modalsArray[i].modalStyle.zIndex--;
        }
    }
    this.modalsArray.splice(index, 1);
}

當close方法被執行時,我需要將其設置為false:isOpenModal:boolean = false; 並在列表組件中提供該事件。

有解決方案的主意嗎?

您可以使用共享服務,例如:

shared.service.ts

聲明一個主題:

openModalSubject : Subject<boolean> = new Subject<boolean>() ;

setModalStatus(isOpenModal : boolean){
 openModalSubject.next(isOpenModal);
}

現在,您可以像下面這樣使用setter來訂閱組件中的主題:

this.sharedService.setModalStatus(isOpenModal);

一旦設置,主題就會將isOpenModal發布到isOpenModal的組件。

在您的組件中,注入shared.service.ts ,您可以像這樣訂閱:

this.sharedService.openModalSubject.subscribe((openModal: boolean) => {
 //do whatever you want with the openModal 
});

這兩個組成部分是child - parent關系嗎?

如果是這樣,您可以只使用input - output方法。

在子組件中:

@Output() modalClosed: EventEmitter = new EventEmitter();
...
this.closed.emit(true);

在父模板中:

<modal-selector (modalClosed)="onModalClose($event)"></modal-selector>

在父組件中:

onModalClose($event) { */ do something when modal closes /* }

我認為您的查詢似乎不清楚,但我正在根據您的問題標題回答

您可以像這樣創建事件發射器的實例

eventEmit = new EventEmitter<your- model>();

現在您可以使用發出函數發出該事件:-

this.eventEmit.emit(here pass the values you want to pass);

在您要偵聽組件的組件中,請使用subscription()方法偵聽事件。

暫無
暫無

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

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