How can I trigger an event emitter in Angular 4?

There are two key components: List and Modal. They do not have a direct child-parent relationship.

The issue arises when clicking on the new button triggers the openModal() method, resulting in a popup opening. I have set this.isOpenModal = true;

  1. List Component openModal() logic snippet:

    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, there is a 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);
}

Upon executing the close() method, I need to ensure that isOpenModal: boolean = false; is also set to false and trigger an event in the List Component.

Any suggestions or solutions for this challenge?

Answer №1

If you need to utilize a shared service, consider implementing the following steps:

shared.service.ts:

Begin by defining a Subject:

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

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

Next, you can subscribe to the subject in your component by using the setter method as shown below:

this.sharedService.setModalStatus(isOpenModal);
.

Upon setting, the subject will broadcast the isOpenModal value to your component where it is subscribed.

In your component, inject the shared.service.ts and subscribe like this:

this.sharedService.openModalSubject.subscribe((openModal: boolean) => {
 //perform actions based on the openModal state
});

Answer №2

Do these two elements have a child-parent relationship?

If they do, you can simply utilize the input-output method.

Within the child component:

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

In the parent template:

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

Inside the parent component:

onModalClose($event) { */ perform actions when modal closes /* }

Answer №3

It appears that your inquiry is a bit unclear, but I will provide an answer based on the title of your question.

To create an event emitter instance, you can use the following code:

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

You can then emit this event by using the emit function like so:

this.eventEmit.emit(enter the values you wish to pass);

In the component where you want to listen for this event, utilize the subscribe() method.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Module 'git-host-info.js' not found

I am currently working on following the official Angular update instructions provided here from version 6.0 to 7.0. However, I have encountered an error. The error message states that my global Angular CLI version is higher (8.2.2) than my local version ( ...

Running the nestjs build command is impossible without the existence of the node_modules folder

Currently, I am in the process of creating a Nestjs micro-service and everything is going smoothly. To run the build found within the dist folder, I use the command below: node dist/main.js However, I encountered a problem where this command does not exec ...

Can I assign a value from the tagModel to ngx-chips in an Angular project?

HTML code: <tag-input class="martop20 tag-adder width100 heightauto" [onAdding]="onAdding" (onAdd)="addInternalDomain($event)" type="text" Ts code: addInternalDomain(tagTex ...

Can parameters with identical union types in a function signature be streamlined to contain only the exact same subtypes using generic types?

// defining a type Combinable with string or number as possible values type Combinable = string | number; // function to check if parameter is a string function isString(param: unknown): param is string { return typeof param === "string"; } /** * Func ...

Is there a way to access popup form values within an Angular Material component?

I created a datatable feature with options to 'ADD' and 'EDIT'. When the user clicks on the add-button, a popup will appear prompting for element name and symbol. After entering the details, the user can click the save button. However, ...

Is it possible for me to learn angular2 using the examples provided on the official website?

Looking to dive into Angular2, but struggling to find comprehensive documentation? I decided to start my journey by studying Angular2 on its official website: https://angular.io/docs/ts/latest/tutorial/ Additionally, I downloaded an Angular2 boilerplate f ...

Unlocking Permissions in Angular 8: A guide to using ngx-permissions for authorization instead of roles

I'm currently utilizing ngx-permissions (https://www.npmjs.com/package/ngx-permissions) within my project to effectively manage user permissions within my application. While it seems straightforward to authorize roles in the HTML section, permissions ...

Scrollbar malfunction in Angular and Bootstrap主 The main scrollbar in Angular and Bootstrap is un

I am currently facing an issue with my Angular app using Bootstrap 5. The main html/body scrollbar does not work when elements overflow the view. I have tried various solutions such as setting a fixed height, adjusting overflow-y to scroll or auto for body ...

Exploring the power of global injectors in Angular 7 for component inheritance

Recently, I have been following a method outlined in a blog post on MSDN to simplify the extension of components without having to include all dependencies in the super() call. However, this approach seems to have ceased working in Angular 7 with Typescrip ...

Utilizing backbone-forms in Typescript: A beginner's guide

Currently in my project, I utilize backbone.js along with typescript. My goal is to incorporate backbone-forms for form creation, however I am unable to locate a typescript definition file (d.ts) for this specific backbone plugin. Despite my attempts to cr ...

"Enhancing Nuxt/Vue 2 Development with Typescript in VS Code's Convenient Props Autocomplete Feature

Transitioning from React to a Nuxt project, I've encountered an issue with setting up autocompletion for props in VSCode (Vetur is installed). Let me illustrate with an example using a prop named 'alignment': ComponentA: <template> ...

Navigating Angular single page application routes within an ASP.NET Web API project

Developed an Angular single-page application with specific routes: /messages /messages/:id By using ng serve, I can navigate to these pages at URLs like localhost:4200/messages and localhost:4200/messages/:id After building the solution, I transferred t ...

What causes the inconsistency in TypeScript's structure typing?

It is well-known that TypeScript applies structure typing, as demonstrated in the following example: interface Vector { x: number; y: number; } interface NamedVector { x: number; y: number; name: string; } function calculateLength(v: Vecto ...

Troubleshooting issue with alignment in Material UI using Typescript

<Grid item xs={12} align="center"> is causing an issue for me No overload matches this call. Overload 1 of 2, '(props: { component: ElementType<any>; } & Partial<Record<Breakpoint, boolean | GridSize>> & { ...

Angular - Display shows previous and current data values

My Angular application has a variable called modelResponse that gets updated with new values and prints them. However, in the HTML, it also displays all of its old values along with the new ones. I used two-way data binding on modelResponse in the HTML [( ...

Issue: Kindly update your dependencies to the latest version of core-js@3

When trying to execute npm start, I encountered an error stating "An unhandled exception occurred: Could not find module "@angular-devkit/build-angular". I attempted to resolve this by installing it using npm install @angular-devkit/build-angular, but the ...

Angular 2 operates in a separate thread, processing custom serializable objects

Is there a way to efficiently handle potentially long computations, such as parsing huge JSON responses, in a non-blocking manner? I experimented with using the multithread.js library for background work using web workers. However, this library requires p ...

Ways to arrange objects to fill up space in a specific sequence

My HTML document contains two child HTML elements within the parent HTML. The parent HTML has a div with a class of .page, which is a large area for the children to occupy. Both children are of the same size and I need them to spawn in a specific order; fo ...

Ways to redirect to a different page following a successful execution of a mutation in React-query

I am facing an issue where a memory leak warning appears when I redirect to another page after a mutation. Despite trying various methods, I have not been able to find a solution. The specific warning message is: Warning: Can't perform a React state ...

Is there a way to inform TypeScript that the process is defined rather than undefined?

When I execute the code line below: internalWhiteList = process.env.INTERNAL_IP_WHITELIST.split( ',' ) An error pops up indicating, Object is possibly undefined. The env variables are injected into process.env through the utilization of the mod ...