PrimeNG - 用户确认的多选

PrimeNG - MultiSelect with user confirmation

我有一个 multiSelect 组件,我希望每当用户更改其选择的选项时显示确认消息,询问他们是否要继续进行该更改,并根据他们的回答回滚更改或应用它们.

遗憾的是,我没有找到任何内置功能来实现这一点,有什么方法可以在(onChange)事件期间应用上述功能吗?

示例

<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版本:12.2.3

PrimeNG 版本:12.1

因此,正如评论部分所述,我最终通过在多选 change 事件发生之前保留值的副本来解决此问题,以便 如果用户在显示的确认对话框中授予权限我们将保留更改,如果用户未授予权限,确认对话框,我们回滚更改 设置为上一个副本的实际值。

代码示例如下:

.html 文件

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

.ts 文件

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;
 }
 });
}

我不知道是否有更好的方法来实现上述场景,但这个解决方案很适合我的情况:)