Search code examples
javascriptangulartypescriptangular7ng-bootstrap

How to pass data from component to ngBootstrap modal in Angular 7?


I have a table with data displayed using ngFor. I need to display an individual row data in a modal on click. i can log it in console by passing the row as click argument but not able to pass it inside the modal.

Assuming the table data is being fetched from a service and the modal is a template reference which is in same component file as the table.

Here is a fiddle created https://stackblitz.com/edit/angular-xr8ud5

I have used angular 1.x and the data was passed through resolve. I am new to Angular and have never worked in ngBootstrap.

Any help is appreciated. Thanks


Solution

  • Passing of data from your component to ngBoostrap modal can be done via Angular's 2-way binding. It is actually the very same way you carry out 2-way binding on Angular 1.x!

    I have made a demo for you.

    First, on your model-basic.ts, you define your model for the modal. Then, you assign the modalContent model property with the table row data.

    modalContent:undefined
      .
      .
    
    open(content, tableRow) {
      this.modalContent = tableRow
      this.modalService.open(content, {ariaLabelledBy: 'modal-basic-title'});
    }
    

    On your modal-basic.html, you can use the {{ ... }} template expression to display the individual properties of your model on your modal itself.

    <ng-template #content let-modal>
      <div class="modal-header">
        <h4 class="modal-title" id="modal-basic-title">Details</h4>
        <button type="button" class="close" aria-label="Close" (click)="modal.dismiss('Cross click')">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
        id: {{ modalContent.id }}
        <br>
        first: {{ modalContent.first }}
        <br>
        last: {{ modalContent.last }}
        <br>
        handle: {{ modalContent.handle }}
      </div>
    </ng-template>