How to open a PrimeNG p-dialog box on a button click and pass data from the component to p-dialog?
Asked Answered
F

1

6

I am working on an Angular migration project where the code is being refactored from AngularJS to Angular 5. Here is the AngularJS code snippet.

HTML

<ul >
    <li ng-if="participant.reports !== null && participant.reports !== undefined" ng-repeat="report in participant.reports">
        <a ng-click="choosePDFLang(participant, report.type, report.name)">
            <img src="i/pdf_image.png"/>{{ report.name | translate }}
        </a>
    </li>
</ul>

JS

$scope.choosePDFLang = function(participant, reportType, reportName)
            $modal.open({
                templateUrl: 'theTemplate'
                controller: 'theController',
                keyboard: true,
                backdrop: 'static',
                scope: $scope
            }).result.then(function() {
            });
        }

As you can see, when an item from the dropdown is clicked, it opened up a modal with its own template and controller which handled all the logic.

Now I have to apply the same logic using Angular 5. My project is using PrimeNG components. I have to use the dialog box <p-dialog></p-dialog>.

My question is : how do I open this dialog box and pass to it all the data when a report hyperlink is clicked ? In AngularJS I could do it easily by calling the $modal.open({}) function and giving it the same scope so now the modals controller has all the data as well.

Flightless answered 18/5, 2018 at 17:25 Comment(0)
M
3

It's easier with Angular2+ and PrimeNG. You just need to define a display property to show or hide the p-dialog and you don't need to create another component.

Now, your code should look something like :

HTML

<ul>
    <li *ngFor="let report of participant.reports">
        <a (click)="choosePDFLang(participant, report.type, report.name)">
            {{ report.name }}
        </a>
    </li>
</ul>

<p-dialog header="{{modalTitle}}" [(visible)]="display">
    {{modalContent}}
</p-dialog>

TS

choosePDFLang(participant, reportType, reportName) {
    this.display = true;
    this.modalTitle = reportName;
    this.modalContent = 'Content of ' + reportName;
  }

See StackBlitz

Don't hesitate if you have any questions !

Minerva answered 18/5, 2018 at 18:32 Comment(1)
Is there a way that this can be achieved without putting a model element template into each of my components? Seems kind of tedious to have to maintain a template in so many placesBarrett

© 2022 - 2024 — McMap. All rights reserved.