Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to pass data to modal ngx-bootstrap and receive return data ? #2290

Closed
tranminhphong0108 opened this issue Jul 27, 2017 · 29 comments · Fixed by #2293
Closed

How to pass data to modal ngx-bootstrap and receive return data ? #2290

tranminhphong0108 opened this issue Jul 27, 2017 · 29 comments · Fixed by #2293

Comments

@tranminhphong0108
Copy link

No description provided.

@tranminhphong0108
Copy link
Author

help me, please!

@tranminhphong0108
Copy link
Author

tranminhphong0108 commented Jul 28, 2017

// How to pass data to modal ngx-bootstrap ???

confirm-popup.component.ts

import { Component, Input } from '@angular/core';
import { BsModalService } from 'ngx-bootstrap/modal';
import { BsModalRef } from 'ngx-bootstrap/modal/modal-options.class';

@Component({
  selector: 'app-confirm',
  templateUrl: `
    <div class="modal-header">
      <h4 class="modal-title pull-left">{{title}}</h4>
      <button type="button" class="close pull-right" aria-label="Close" (click)="bsModalRef.hide()">
        <span aria-hidden="true">&times;</span>
      </button>
    </div>
    <div class="modal-body">
      {{message}}
    </div>
    <div class="modal-footer">
      <button type="button" class="btn btn-default" (click)="bsModalRef.hide()" translate="cancel"></button>
      <button type="button" class="btn btn-success" (click)="clickOk()" translate="ok"></button>
    </div>`,
  providers: [BsModalService]
})

export class ConfirmPopupComponent {
  @Input() title: string = 'Modal with component';
  @Input() message: string = 'Message here...';

  constructor(public bsModalRef: BsModalRef) { }

  public clickOk() {
    console.log("Click ok...");
  }
}

helper.service.ts

import { BsModalService } from 'ngx-bootstrap/modal';
import { BsModalRef } from 'ngx-bootstrap/modal/modal-options.class';
import { ConfirmPopupComponent } from '../../../shared/confirm-popup/confirm-popup.component';

export class HelperService {
  constructor(private modalService: BsModalService) {
  }
  showConfirm(title?: string, message?: string) {
       let bsModalRef = this.modalService.show(ConfirmPopupComponent, { animated: true, keyboard: true, backdrop: true, ignoreBackdropClick: false });
       console.log("bsModalRef: ", bsModalRef);
  }
}

sign-in.component.ts

showConfirm() {
    this.helper.showConfirm("Confirmation", "How to pass data to modal?");
}

"Confirmation" and "How to pass data to modal?" not show in modal. How to show...???

@tranminhphong0108 tranminhphong0108 changed the title How to pass data to modal ngx-bootstrap ? How to pass data to modal ngx-bootstrap and receive return data ? Jul 28, 2017
valorkin pushed a commit that referenced this issue Jul 28, 2017
@mpeguero
Copy link

mpeguero commented Dec 29, 2017

on Parent component
import { Modal, BSModalContext } from 'ngx-modialog/plugins/bootstrap'; import { overlayConfigFactory } from 'ngx-modialog';

var dataObject = {data1: "ba vbal", data2 :"bla bla"}; this.modal.open(urmodalCpmponent, overlayConfigFactory({data: dataObject}, BSModalContext))
on Model Component
import { DialogRef } from 'ngx-modialog';

constructor(public dialogRef: DialogRef){
let context:any = dialogRef.context;
this.detail = context.data'
}

@MgSam
Copy link

MgSam commented Feb 7, 2018

@tranminhphong0108 I don't understand your example of the modal service. Your helper.service.ts has two parameters title and message but then never does anything with either of the parameters. So how does that data actually get to the ConfirmPopupComponent?

The examples on https://valor-software.com/ngx-bootstrap/#/modals have the same problem.

@belalothman
Copy link

@MgSam did you find any solution for this problem?

@zymr-keshav
Copy link

zymr-keshav commented Mar 13, 2018

pass data with initialState params

const initialState = { message, title };

		let bsModalRef = this.modalService.show(ConfirmPopupComponent, Object.assign({}, this.modalConfig, { class: 'modal-sm', initialState })
		);

note: there would be template instead of templateUrl in your code @tranminhphong0108

@lonekawboy
Copy link

How does this help me receive information back from the calling component? I'm looking for an example of where a modal is called from one component, performs an operation (like add an item) and then the calling component is informed of the add and can then perform operations as needed. Seems like something that is a quite common need.

@zymr-keshav
Copy link

here is how you send information back to parent component ( calling component)

  1. create a EventEmitter on confirmPopupComponent
	@Output() action = new EventEmitter();
  1. now on click ok button emit the output from confirmPopupComponent
      public clickOk() {
		this.loading = true;
		this.action.emit(true); << here you can send object  instead of true
	}
  1. now from calling component ( i.e. parent component) you can get this way

here key action will be same as Outout emit

let bsModalRef = this.modalService.show(..);
bsModalRef.content.action.take(1).subscribe((value) => {
		console.log(value) // here you will get the value
		});

hope it will help

@jose-torres-marin
Copy link

@zymr-keshav Awesome. That should really be part of the official docs.

@BBaysinger
Copy link

BBaysinger commented Mar 23, 2018

How does the component receive the parameters?

@zymr-keshav
Copy link

zymr-keshav commented Mar 24, 2018

set @Input() parameter in the popup component to access the property in initialState

for eg:
in Parent Component

const initialState = { message: 'popup message', title:'popup title'};
let bsModalRef = this.modalService.show(ConfirmPopupComponent, Object.assign({}, this.modalConfig, { class: 'modal-sm', initialState })

in confirmPopupComponent

@Input() message: string = 'Message here...'; // we can set the default value also
@Input() title: string = 'default title';

@stiofand
Copy link

stiofand commented Apr 6, 2018

Sorry, but I have exactly the same issue, and its not clear at all from the docs, (or above how one uses the initial state property in the component that is passed to the Dialog show event.

I pass in an object with properties I need (initialState) along with my component I wish to show. However, there is nothing I can do to reference anything in that component from initial state. I still cant figure it out from your solutions above either.

@zymr-keshav
Copy link

you can pass any data from initialState property only, that is fixed name of the property.

@stiofand
Copy link

stiofand commented Apr 9, 2018

you can pass any data from initialState property only, that is fixed name of the property.

Yes, this is what the docs say, but even in the example given with the documentation, initialState or any named property of initialState is always null.

@davyvanlaere
Copy link

I think the handling of modals in ngx-bootstrap could be much improved ... i understand that i can put my own eventemitters on my modal component to signal return values, but what about when the user exits the dialog via the ESC key of by clicking outside of the dialog bounds? I then have to combine my custom eventemitters with those exposed on the BsModalService. I think it would make more sense if the OnShow/OnShown/... events were put on the BsModalRef instead of the global service ...

@marcosdimitrio
Copy link

To help with the issue of pressing the ESC key or clicking outside the dialog box and still receiving a result, I wrote a question/answer on StackOverflow with code that handles it. It's explained there, so I won't repost it here, check it out:

https://stackoverflow.com/questions/50207100/how-can-i-pass-and-receive-data-to-from-a-ngx-bootstrap-modal

@Upasana242
Copy link

const initialState = { message: 'popup message', title:'popup title'}; let bsModalRef = this.modalService.show(ConfirmPopupComponent, Object.assign({}, this.modalConfig, { class: 'modal-sm', initialState })
This is not working for me. I am getting an empty dialog box.
I am using it in a function. Like:
somefunction(popupMessage, popupTitle){ const initialState = { message:popupMessage, title: popupTitle }; this.modalService.show(ConfirmPopupComponent, Object.assign({}, this.modalConfig, { class: 'modal-sm', initialState });

@Parnianmhr
Copy link

@marcosdimitrio Your answer is perfect, thanks. But how should I return a Boolean instead of string to use it in my canDeactivate guard function? Any Idea?

@zymr-keshav
Copy link

currently returning a boolean actually, check this.action.emit(true);

@subhanBashaa
Copy link

Thanks a lot, Its worked for me

@shakalya195
Copy link

I am assigning the end result of events model at this.data and recieving data to its parent listing component by subscribing the modelService.onHide event.
This was regenerating each time i closes the model like at fifth time the subscription will be show 5 time. so i put unsubscribe right after reading.
This works perfect from me.

I am creating an event in addEvents model.
Hitting the API and getting the success event model updated on this.data.
On closing the model my subscription works and it updates the my current listing page.

  addEvent(){
    this.bsModalRef = this.modalService.show(AddEventComponent, {});
    let newSubscriber = this.modalService.onHide.subscribe(r=>{
      newSubscriber.unsubscribe();
      console.log('DATA',this.bsModalRef.content.data);
    });
  }

@akash-potdar7
Copy link

pass data with initialState params

const initialState = { message, title };

		let bsModalRef = this.modalService.show(ConfirmPopupComponent, Object.assign({}, this.modalConfig, { class: 'modal-sm', initialState })
		);

note: there would be template instead of templateUrl in your code @tranminhphong0108

passing data to the component is fine. The real problem people are looking for is receiving data back from the modalComponent

@popsovy
Copy link

popsovy commented Apr 22, 2019

Couldn't you use the initialState to create a callback method. Similar how it's done here.

@ghost
Copy link

ghost commented Jun 11, 2019

In your Service, create this function

openConfirmDialogBox() {
        this.modalRef = this.modalService.show(DemoModalComponent);
        this.modalRef.content.action.take(1)
            .subscribe((value) => {
                console.log(value) // here value passed on clicking ok will be printed in console. Here true will be printed if OK is clicked
                return value;
             }, (err) => {
                 return false;
        });
    }

then in your demo-modal.component.ts create an EventEmitter

 @Output() action = new EventEmitter();
 public onClickOK() {
    this.action.emit(true); //Can send your required data here instead of true
 }
 public onClickCANCEL() {
    this.action.emit(false); //Can send your required data here instead of true
 }

@imoyao
Copy link

imoyao commented May 25, 2020

here is how you send information back to parent component ( calling component)

  1. create a EventEmitter on confirmPopupComponent
	@Output() action = new EventEmitter();
  1. now on click ok button emit the output from confirmPopupComponent
      public clickOk() {
		this.loading = true;
		this.action.emit(true); << here you can send object  instead of true
	}
  1. now from calling component ( i.e. parent component) you can get this way

here key action will be same as Outout emit

let bsModalRef = this.modalService.show(..);
bsModalRef.content.action.take(1).subscribe((value) => {
		console.log(value) // here you will get the value
		});

hope it will help


Thank you very much for your code, I tried it and returned the following error:

Uncaught Error: Uncaught (in promise): TypeError: bsModalRef.content.sendToLocateParent.take is not a function

It seems that the Error is caused by an asynchronous call(toPromise),I must get the result of getDisklight() function first and then show the modal,how can i deal with this?

Finally, I used the following code above, it works for me, but I still wonder why the above code go wrong?thank you very much!
here is my codes:

  async LocateDiskAction(lightState) {
    this.clickModal = true  // set click action to true
    let lightDisk = await this.getDisklight(lightState)
    let initialState = {
      lightDisk: lightDisk,
      action: lightState,
      hostName: this.hostName,
    };
    let modalConfig = { animated: true, keyboard: true, backdrop: true, ignoreBackdropClick: false }
    let bsModalRef = this.modalService.show(DiskLocateModalComponent,
      Object.assign({}, modalConfig, {initialState
      })
    );
   bsModalRef.content.sendToLocateParent.take(1).subscribe((value) => {
     console.log(value, '--------------------') // here i get the error instead the value
    });
  }

getDisklight(diskSignal) {
    return this.client.get(`api/disk/${this.hostName}?disk_status=${diskSignal}`).toPromise();
  }

@krunal8123
Copy link

pass data with initialState params

const initialState = { message, title };

		let bsModalRef = this.modalService.show(ConfirmPopupComponent, Object.assign({}, this.modalConfig, { class: 'modal-sm', initialState })
		);

note: there would be template instead of templateUrl in your code @tranminhphong0108

pass data with initialState params

const initialState = { message, title };

		let bsModalRef = this.modalService.show(ConfirmPopupComponent, Object.assign({}, this.modalConfig, { class: 'modal-sm', initialState })
		);

note: there would be template instead of templateUrl in your code @tranminhphong0108

passing data to the component is fine. The real problem people are looking for is receiving data back from the modalComponent

What is this.modalConfig ? or how to set value of this.modalConfig ?

@ikubij
Copy link

ikubij commented Dec 1, 2020

here is how you send information back to parent component ( calling component)

  1. create a EventEmitter on confirmPopupComponent
	@Output() action = new EventEmitter();
  1. now on click ok button emit the output from confirmPopupComponent
      public clickOk() {
		this.loading = true;
		this.action.emit(true); << here you can send object  instead of true
	}
  1. now from calling component ( i.e. parent component) you can get this way

here key action will be same as Outout emit

let bsModalRef = this.modalService.show(..);
bsModalRef.content.action.take(1).subscribe((value) => {
		console.log(value) // here you will get the value
		});

hope it will help

This works, but remove take(1) . At least that is what worked for me

@HimalPant
Copy link

pass data with initialState params

const initialState = { message, title };

		let bsModalRef = this.modalService.show(ConfirmPopupComponent, Object.assign({}, this.modalConfig, { class: 'modal-sm', initialState })
		);

note: there would be template instead of templateUrl in your code @tranminhphong0108

What do we use .show(ConfirmPopupComponent,...), what is the use of this ConfirmPopupComponent ??

@anurag-roy
Copy link

Does anyone know how I can pass initialData and access it if using a template instead of a component?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging a pull request may close this issue.