James Delaney
James Delaney

Reputation: 1776

How to emit event emitter in angular 4?

There is two component List and Modal:

They are not in child - parent relationship.

Problem is when you click on the new button then openModal() method is called, you get popup opened. And I set this.isOpenModal = true;

  1. List Component openModal() part of logic:

    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);
        }
    }
    

In the Modal-Component I have close() method:

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);
}

When close method is exectuted I need this to be setup on false: isOpenModal: boolean = false; And provide that event in the List Component.

Any idea for solution?

Upvotes: 1

Views: 5351

Answers (3)

CruelEngine
CruelEngine

Reputation: 2841

You can use a shared service like :

shared.service.ts :

declare a Subject :

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

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

Now you can subscribe to the subject in your component after using the setter like this :

this.sharedService.setModalStatus(isOpenModal); .

As soon as you set , the subject will publish the isOpenModal to your component where it is subscribed .

in your component , inject the shared.service.ts and you can subscribe like :

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

Upvotes: 3

bhavesh27
bhavesh27

Reputation: 94

I think your query seems somewhat unclear but i am answering according to your question title

you can create an instance of event emitter like this

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

Now you can emit this event using emit function:-

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

in the component where you want to listen to it use the subscribe () method to listen to event.

Upvotes: 2

Roberto Zvjerković
Roberto Zvjerković

Reputation: 10137

Are those two component in child - parent relationship?

If so, you can just use input - output method.

In child component:

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

In parent template:

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

In parent component:

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

Upvotes: 2

Related Questions