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

Using an asynchronous pipe filter with the ngFor loop in Angular 2 for efficient data

I have a JSON array that I need to iterate through in order to display data using an NGfor Loop. My goal is to apply filters after the data has been loaded to refine the results. The issue I am facing is that my pipe filter is returning 'cannot read p ...

Drawing a real-time curve using Phaser 3

After reading the article at the following link, I am attempting to create a dynamic curve showing where a bullet intersects with the land in my game before firing. Any suggestions or ideas on how to achieve this would be greatly appreciated. Thank you. L ...

Typescript defines types for parameters used in callbacks for an event bus

Encountering a TypeScript error with our custom event bus: TS2345: Argument of type 'unknown' is not assignable to parameter of type 'AccountInfo | undefined'. Type 'unknown The event bus utilizes unknown[] as an argument for ca ...

The issue encountered during the construction of the nrwl library project is that object Object is not recognized as a PostCSS

We are currently facing an issue with our nrwl-nx workspace library project (based on Angular 8) that contains 3-4 angular libraries. While the ng serve function works properly, we have started encountering errors when trying to run ng build my-lib. On ou ...

The value of an Angular array seems to be disappearing after being copied to another array and then cleared

I have encountered an issue while working with arrays. I am initializing two arrays - one with some values and another as empty. However, when I assign the items from the first array to the second array and then clear the first array, it unexpectedly clear ...

Encountering issues with Angular2 App when attempting to load simulated data using a Promise causes malfunction

Looking to implement my mocked data loading using a promise, similar to the approach shown in the Angular2 Tutorial found here. Service (Mock): import { Injectable } from '@angular/core'; import { ERGEBNISSE } from "./mock-ergebnisse"; @Inject ...

Deployment error on Google App Engine for Angular Universal 13 and Angularfire 7

Upgrading my app from Angular 12 to Angular 13 has caused deployment issues on Google App Engine. The error message reads: ERROR: (gcloud.app.deploy) Error Response: [9] An internal error occurred while processing task /app-engine-flex/flex_await_healthy/ ...

Angular Delight: Jaw-Dropping Animation

After setting up my first Angular project, I wanted to incorporate Angular Animations to bring life to my content as the user scrolls through the page. I aimed to not only have the content appear on scroll but also implement a staggering animation effect. ...

Is there an issue with TypeScript and MUI 5 sx compatibility?

Here's a question for you: Why does this code snippet work? const heroText = { height: 400, display: "flex", justifyContent: "center", } <Grid item sx={heroText}>Some text</Grid> On the other hand, why does adding flexDirection: "c ...

How can we prevent users from changing URLs or accessing pages directly in Angular 7 without using authguard?

Hey there! I am trying to find a way to prevent users from accessing different pages by changing the URL, like in this scenario. Is there a method that can redirect the user back to the same page without using Authguard or any Modules? I have a StackBlit ...

Enums are not recognized by TypeScript when used within an array

I have defined an enum as follows: export enum Roles { ADMIN, NONE; } An object is being used which utilizes this enum. The structure of the object is: export interface User { name: string; roles: Roles[]; } Upon fetching this object via a web r ...

How can I effectively retrieve a value from Ionic storage and use it as an authorization token instead of receiving the promise "Bearer [object Promise]"?

In my Ionic 4 angular project, the storage.get('token').then() function returns a promise object instead of the refresh token. For JWT authentication, I send the access token as the bearer token in the authorization headers using an HTTP interce ...

It appears that Typescript mistakenly interprets a class or type as a value, indicating that "'Classname' is being referred to as a value but used as a type here."

I want to pass an Object of a React.Component as "this" to a Child React.Component in the following way: component 1 file: class Comp1 extends React.Component<...,...> { ... render() { return (<Comp2 comp1={this}/> ...

What steps can I take to resolve the issue of the Error value not being iterable?

I encountered an issue in my table where I get the error message value is not iterable when there is no value to iterate through. How can I handle this error in my code? Snippet of Code: if (null != data && data) { data = data.map((item) => ...

Using static methods within a static class to achieve method overloading in Typescript

I have a TypeScript static class that converts key-value pairs to strings. The values can be boolean, number, or string, but I want them all to end up as strings with specific implementations. [{ key: "key1", value: false }, { key: "key2&qu ...

"Seeking advice on how to nest a service provider within another one in AngularJS 2. Any

I am faced with a product and cart list scenario. Below is the function I have created to iterate through the cart list and retrieve the specific product using its ID. getCartList(){ this.cart = CART; this.cart.forEach((cart: Cart) => ...

Issue with accessing custom method in subclass in Typescript

Recently delving into TypeScript, I decided to subclass Error and add a new method called getCode() in my MyError class. export class MyError extends Error { public code: number; constructor(code: number, message?: string) { super(mes ...

The properties 'paginator' and 'sort' are missing an initial value

Struggling to implement a form filter similar to the one shown on a specific website, I encountered some code issues in my own environment. Check out this data table example with sorting, pagination, and filtering. @ViewChild(MatPaginator) paginator: MatP ...

Trustpilot: The function window.Trustpilot.loadFromElement does not exist in Safari

I am looking to integrate 3 TrustPilots into my Angular application. import { Component, Input, OnInit } from '@angular/core'; declare global { interface Window { Trustpilot: any; } } window.Trustpilot = window.Trustpilot || {}; @Component ...

Guide to utilizing the Angular Material 2 documentation without an internet connection

Is there a way to access the Angular Material 2 documentation offline? I would like to have it available without needing an internet connection. What alternatives or solutions are there for this? ...