1. 程式人生 > >Angular2+PrimeNg踩坑之 p-confirmDialog (彈出框)

Angular2+PrimeNg踩坑之 p-confirmDialog (彈出框)

注:下面我介紹的是 p-confirmDialog(對話方塊) 在完整的專案中的用法,,以及在巢狀使用的時候的用法,關於在單個頁面中的用法可以參考官網。官網地址:https://www.primefaces.org/primeng/#/

1、引入ConfirmDialogModule模組

在專案中全域性引入ConfirmDialogModule模組,需要在app.modules.ts檔案引入

import {
  ConfirmDialogModule,
  ConfirmationService
} from 'primeng/primeng';

Import: [

ConfirmDialogModule],

Providers: [ ConfirmationService ]

2、插入標籤

在專案中,一般是將標籤放在檔案main.component.html檔案中,以便於用於全域性。也就是說,你只需要在main.component.html中定義一次就可以在整個專案中使用了。

語法:

<p-confirmDialog [appendTo]="'body'" [acceptLabel]="'確定'" [rejectLabel]="'取消'"></p-confirmDialog>

3、單次使用(不巢狀使用)

(1)在當前頁引入

import {ConfirmationService} from 'primeng/primeng';

(2)依賴注入

constructor(private confirmationService: ConfirmationService) {}

(3)函式

在你需要彈出框的位置寫函式:

this.confirmationService.confirm({
  message: '彈出框的詳細內容',
  header: '彈出框的標題',
  icon: 'fa fa-info-circle'

});

在該函式中的headermessage等性質你可以參考官網,根據你的需要來新增。在此我就不贅述了。

官網地址:https://www.primefaces.org/primeng/#/confirmdialog

4、巢狀使用

巢狀使用相對而言就複雜很多了。

前兩個步驟跟上述的單次使用一樣,在此不再贅述。

oncomfirme(){

this.confirmationService.confirm({
  message: '彈出框的詳細內容',
  header: '彈出框的標題',
  icon: 'fa fa-info-circle',
  acceptLabel: '',
  rejectLabel: '',
  accept: () => {
    this.onNewLocationInfo();
  }
});

}

onNewLocationInfo(msg){

this.confirmationService.confirm({
  message: '彈出框的詳細內容',
  header: '彈出框的標題',
  icon: 'fa fa-info-circle',
  acceptLabel: '',
  rejectLabel: ''
 });

}

到此為止一個彈出框的巢狀完成了。你會發現在關閉第一個彈出框後,第二個彈出框不會出現,而且還不會抱任何的錯。這是什麼原因呢?

開始的時候我就說過,在專案中,一般是將標籤放在檔案main.component.html檔案中,以便於用於全域性。也就是使所有的彈出框用的都是同一個彈出框標籤。

當我們單擊第一個彈出框的“是”按鈕的時候,會呼叫函式 onNewLocationInfo();彈出第二個彈出框,並關閉第一個彈出框。因此,我們只能看到第一個彈出框關閉,而看不到第二個框開啟,因為第二個彈出框在被開啟的同時就被關閉了。該如何解決這個問題呢?

很簡單,在你需要使用巢狀彈出框的元件的HTML檔案中新增標籤p-confirmDialog,並給一個key值。

<p-confirmDialog [appendTo]="'body'" [key]="'newLocationConfirm'"></p-confirmDialog>

 

<p-confirmDialog [appendTo]="'body'" [key]="'mapConfirm'"></p-confirmDialog>

然後,在你的函式中將key值新增進去。

oncomfirme(){

this.confirmationService.confirm({
  message: '彈出框的詳細內容',
  header: '彈出框的標題',
  icon: 'fa fa-info-circle',

key: 'newLocationConfirm',
  acceptLabel: '',
  rejectLabel: '',
  accept: () => {
    this.onNewLocationInfo();
  }
});

}

 

onNewLocationInfo(msg){

this.confirmationService.confirm({
  message: '彈出框的詳細內容',
  header: '彈出框的標題',
  icon: 'fa fa-info-circle',

key: 'mapConfirm',
  acceptLabel: '',
  rejectLabel: ''
 });

}

這樣問題就得到了解決。標籤中的key值就相當於關鍵字的存在,通過這個key來指定用哪個標籤,而不是用那個全域性的標籤。