How to pass parameteres to modal?

robert picture robert · Dec 14, 2016 · Viewed 26.9k times · Source

That's the way I use the ng2-bootstrap modal:

import {Component} from '@angular/core';
import {NgbModal} from '@ng-bootstrap/ng-bootstrap';

@Component({
  selector: 'add-customer-modal',
  template: `
    <template #test let-c="close" let-d="dismiss">
      <div class="modal-header">
        <button type="button" class="close" aria-label="Close" (click)="d('Cross click')">
          <span aria-hidden="true">&times;</span>
        </button>
        <h4 class="modal-title">Modal title</h4>
      </div>
      <div class="modal-body">
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" (click)="c('Close click')">Close</button>
      </div>
    </template>
    <button type="button" class="btn btn-primary btn-sm" (click)="open(test)"><i class="fa fa-plus"></i> <i class="fa fa-user-o"></i></button>
  `
})
export class AddCustomerModal {

  constructor(private modalService: NgbModal) {}

  open(content) {
    this.modalService.open(content, { size: 'lg' }).result.then((result) => {
      console.log(result);
    }, (reason) => {
      console.log(reason);
    });
  }
}

I'am a little bit confused, because I thought the content is used to pass parameters to the modal. But in my opinion it's only the name the open method needs to find the correct template?

So how can I pass parameters?

Answer

Sadiq Ali picture Sadiq Ali · Jun 12, 2017

Anyone still stumbling onto this might find this handy, all you need to do is declare a field inside your ModalComponent like this:

 modalHeader: string;
 advertiser: Advertiser;

You can set these fields by doing the following when you are opening a modal.

advertiserModalShow() {
    const activeModal = this.modalService.open(AdvertiserModal, { size: 'lg' });
    activeModal.componentInstance.modalHeader = 'Advertiser';
    activeModal.componentInstance.advertiser = this.selectedAdvertiser;
}

In your template you can access them like this:

value={{advertiser.code}}

Hope this helps.