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

yugrac picture yugrac · May 18, 2018 · Viewed 7.6k times · Source

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.

Answer

Antikhippe picture Antikhippe · May 18, 2018

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 !