angularprimengmulti-select

PrimeNG - MultiSelect with user confirmation


I have a multiSelect component and I want whenever user changes its selected options to show a confirmation message, asking whether they want to proceed with that change or not and according to their answer rollback changes or apply them.

Unfortunately I did not find any built-in functionality to achieve this, is there any way I can apply the functionality described above during the (onChange) event?

Example:

<p-multiSelect [options]="availableLanguages" [(ngModel)]="languages" 
                               name="languages"
                               (onChange)="myChangeFunction($event);"
                               class="multiselect-custom">


myChangeFunction(event: any) {
  this.confirmationService.confirm({
    message: 'Are you sure?',
    acceptLabel: 'Yes',
    rejectLabel: 'No',
    accept: () => {
       // do that change if user presses "Yes"
    },
    reject: () => {
      // rollback the change if user presses "No"
    }
  });
 }

Angular version: 12.2.3

PrimeNG version: 12.1


Solution

  • So as described in the comments section, I ended up doing a custom solution to solve this problem, by keeping a copy of the values before the multiselect change event takes place so that if the user gives permission on the confirmation dialog shown, we keep the changes and if the user does not give permission on the confirmation dialog, we rollback the changes by setting to the actual value the previous copy.

    Code Example shown below:

    .html file

    <p-multiSelect [options]="availableLanguages" [(ngModel)]="languages" 
                               name="languages"
                               (onChange)="myChangeFunction($event);"
                               class="multiselect-custom">
    

    .ts file

    languages = [....]; // this is our variable carrying the actual values
    languagesCopy = []; // this is our "copy-variable" helper for rollback  
    
    
    ngOnInit(): void {
      // initialize the "languagesCopy" to have same value with "languages"
      this.languagesCopy = this.languages;
    }
    
    myChangeFunction(event: any) {
      this.confirmationService.confirm({
      message: 'Are you sure?',
      acceptLabel: 'Yes',
      rejectLabel: 'No',
      accept: () => {
       // do nothing since the change has already take place
     },
     reject: () => {
      // rollback the change if user presses "No"
      // "languages" have already changes since it is binded through 
      //  [ngModel] from the multiSelect change event, so set the languages 
      //  variable back to its previous value stored in "languagesCopy"
       this.languages = this.languagesCopy;
     }
     });
    }
    

    I do not know if there is any better way to achieve the scenario described above but this solution works fine for my case :)