Pause until the user selects either the confirm or deny option before proceeding with the next action

As a beginner in Angular, I am seeking help with my code structure. I have three files: WarningComponent (which displays a warning modal using Bootstrap), modalService (responsible for opening modals), and votingComponent.

Within the votingComponent, there is a button labeled "vote." When this button is clicked, the WarningComponent opens (using the modalService). The WarningComponent contains two buttons: Confirm and Deny.

My objective is to trigger the function postSelectionChoice() in the votingComponent when the user clicks on Confirm.

I attempted to achieve this using Promise and Observable, but encountered issues or possibly implemented them incorrectly...

votingComponent.ts

  private showWarning() {
    // This method is executed when the user clicks Vote
    this.modalService.openModal(ModalType.WARNING,"test");
  }

  private postSelectionChoice() {
   // This should be triggered when the user confirms in the WarningComponent

  }

Modal.Service.ts

@Injectable()
export class ModalService {

  constructor(private modalService: NgbModal) { }

  public openModal(modal: ModalType, message: string) {
    let modalRef :NgbModalRef = null;
    if(modal == ModalType.ALERT) {
      modalRef = this.modalService.open(AlertModalComponent);
    } else if (modal == ModalType.WARNING) {
      modalRef = this.modalService.open(WarningModalComponent);
    } else if (modal == ModalType.SUCCES) {
      modalRef = this.modalService.open(SuccesModalComponent);
    }
    modalRef.componentInstance.message = message;
  }

  // Attempted implementation for reference...
  public getConfirmation(status: Warningstatus) : Promise<Boolean> {
    return new Promise((resolve, reject) => {
      if(status == Warningstatus.YES) {
          console.log("trueeee");
          resolve(true);
      } else if(status == Warningstatus.NO) {
        console.log("falseeee");
          resolve(false);
      }
  });
  }
}

WarningComponent.ts

export class WarningModalComponent {

  @Input() message;

  constructor(public activeModal: NgbActiveModal) {
  }

  public confirmButton() {
    // This method is called when the user clicks the confirm button
  }

}

Answer №1

component.ts

import { NgbModal, NgbModalOptions } from '@ng-bootstrap/ng-bootstrap';

Initialize modal service:

constructor(        
    private _modalService: NgbModal
) { }

Show modal on button click:

showCustomModal() {
    const modalRef = this._modalService.open(CustomModalComponent, { size: 'lg' });
    modalRef.componentInstance.passDataToModal = yourdata;
    modalRef.result.then((result) => {
        if (result) {                
            console.log("Modal closed with true value");
        }
    },
        (reason) => { });
}

In CustomModalComponent.ts:

import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';

    constructor(
        public activeModal: NgbActiveModal
    ) { }

    onClose() {
        this.activeModal.close(false);
    }

    onDismiss() {
        this.activeModal.dismiss(false);
    }

    sendDataAndClose() {
        // process data and send it back to parent component
        this.activeModal.close(returneddatatoparent);
    }

Answer №2

modal-Control-service.ts

 public showConfirmModal: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);
 simpleObservable: Observable<{}>;
 reAction: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false); 

 confirmDialog(action: string, objectValue: string, objectType: string) {

  let simpleObservable;
  const reAction = this.reAction;
  const promise = Promise(function (resolve, reject) {

  simpleObservable = new Observable((observer) => {

    observer.complete();
    if (reAction.value !== null) {
      resolve(reAction.value);
    }
    reject('Invalid action');
  });

  });

  this.simpleObservable = simpleObservable;
  this.showConfirmModal.next(true);
  return promise; 
 }

 confirm() {
  this.reAction.next(true);
  this.subscribe = this.simpleObservable.subscribe();
  this.subscribe.unsubscribe();
 }

 decline() {
  this.reAction.next(false);
  this.subscribe = this.simpleObservable.subscribe();
  this.subscribe.unsubscribe();
  }

modal-component.ts

 modalRef: BsModalRef;
     constructor(public modalControl: ModalControlService, public modalService: BsModalService, ) {

modalControl.showConfirmModal.subscribe((nextValue) => {
  // this will happen on every change
  if (nextValue) {
    this.modal.show();
  }
});
  }

While working with the ngx-bootstrap library, I am utilizing modals.

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

What could be causing the promise in Angular 8 to return an undefined value, even though it was correctly logged just before it was resolved?

MODIFY I checked to see if the script is entering the addHousehold() if condition here: addHouseholdPromise.then((res) => { console.log("Promise HH: "+res) if (res != "add_hh_fail") { console.log("success: "+res) return res ...

Function editing error

Attempting to retrieve user data for editing in the form is causing an error related to the line where the data is being assigned: **** this.user = data This is the content of edit-user.component.ts: import { Component, OnInit } from '@angular/core ...

An error occurs when attempting to use object mapping and the rest operator in a return statement due to

I've encountered a type mismatch error in my TypeScript project using Prisma while attempting to return an object with mapped properties in the getPool method. Let's take a look at the code snippet causing the issue: public async getPool({ id, v ...

Exploring multiple states within an interval function in React Native

I'm struggling to find the right words for this question. I've encountered an issue where I need to constantly check and update a complex state object within an interval loop in my program. To simplify, let's say it consists of just a counte ...

Utilize the power of relative import by including the complete filename

When working on my TypeScript project, I have noticed that to import ./foo/index.ts, there are four different ways to do it: import Foo from './foo' // ❌ import Foo from './foo/index' // ❌ import Foo from './foo/i ...

Numerous Progressive Web Apps within one domain

Can I host several PWAs on the same endpoint? For example, if I have three different PWAs under one root, can the root host these PWAs in a way that switching between them via links or menus does not open a new window? Currently, when I click on a differen ...

The variable "$" cannot be found within the current context - encountering TypeScript and jQuery within a module

Whenever I attempt to utilize jQuery within a class or module, I encounter an error: /// <reference path="../jquery.d.ts" /> element: jQuery; // all is good elementou: $; // all is fine class buggers{ private element: jQuery; // The nam ...

Guide on displaying toaster notifications using promises in Angular 2

Hey everyone, I've encountered a problem with promises while handling a 500 internal server error. I have set up Promises to handle post and get services, but when catching the 500 response, I can't seem to display it in a toaster. Here's my ...

Creating a custom Angular HTTP interceptor to handle authentication headers

Necessity arises for me to insert a token into the 'Authorization' header with every HTTP request. Thus, I created and implemented an HttpInterceptor: @Injectable() export class TokenInterceptor implements HttpInterceptor { constructor(public ...

What is the best way to programmatically define the value for the MaterialUI grid size property using TypeScript?

Is there a way to dynamically pass a value to the Grid size props like XL in TypeScript? For instance, *Update for further clarification import Grid, { GridSize } from "@material-ui/core/Grid"; let value: GridSize = 12/4; xl={value} Error: Type &apos ...

Implementing a variable for an array in Angular 4: A step-by-step guide

I need help determining the correct value for skill.team[variable here].name in Angular, where all team names are retrieved from the skill. Below is the code snippet: HTML <select [(ngModel)]="skill.teams[1].name" name="teamName" id="teamName" class= ...

What is the process for adding connected entities in MikroORM?

I am encountering difficulties in inserting related elements into each other. I believe I may be approaching it incorrectly. Here is an example of how I am attempting to do so. Mikro does not appear to set the foreign key in the dec_declinaison table. /* ...

I am deciding between using CommonJS or ES module for my sub packages in a Yarn workspace for my Next.js project. Which one

Currently working on a Next.js monorepo project using TypeScript and yarn workspace. Within the yarn workspace, there are two packages: /web and /api. The /web package is a next.js project, while /api serves as a shared subpackage utilized by /web. /my-pr ...

How to bring in a class that was exported using `export = uuid` in Typescript

I'm facing a challenge while working with the node_module called uuid-js in TypeScript. After installing both the module and its typings, I am unsure how to properly import the module. Question: What is the correct way to import the module? The func ...

How to Retrieve the Root Path of a Project in a Cypress Test Script

Within my Nx workspace, I am currently testing an app using Cypress. The spec file I'm working with is nested within a subfolder structure like this: ${PROJECT_FOLDER}/apps/${APP_NAME}/cypress/e2e/${SOME_FOLDER}/test.cy.ts I need to find the absolut ...

Leverage the generic parameter type inferred from one function to dynamically type other functions

I am in the process of developing an API for displaying a schema graph. Here is a simplified version of what it entails: interface Node { name: string; } type NodeNames<T extends Node[]> = T[number]["name"]; // Union of all node names as strings ...

Troubleshooting issues with Angular Material's basic mat-autocomplete functionality

After spending more than 72 hours trying to resolve this issue, I have hit a roadblock. Oddly enough, when I create a minimal working example in stackblitz, everything functions perfectly. The problem lies within a simple mat-autocomplete embedded within ...

Struggling with parsing JSON files in Angular 5?

Hello, I am currently working on a web application using Angular 5. I am facing an issue while trying to read a JSON file through an HTTP call. Despite the file being in the same folder, I keep getting a 404 error. Here is a snippet from my service.ts file ...

Leveraging the Map function with Arrays in TypeScript

Is there a way to dynamically render JSON data into a component using array.map in Typescript? I am running into an error with the code snippet below. const PricingSection: FC<IProps> = ({ icon, title, price, user, observations, projects, intervie ...

What is the method for accessing the constructor type of an interface?

I am familiar with accessing a property type of an interface using interfaceName['propertyName'], but how can we access the constructor? For example: interface PromiseConstructor { new <T>(executor: (resolve: (value?: T | PromiseLike& ...