Issue
I would like to declare an application wide PrimeNg (i.e: inside app.component.html) and then being able to display it by calling ConfirmationService.confirm() from another service.
Please find the code HTML in app-component.html
<p-confirmDialog
[key]="mainDialog"
class="styleDialog"
[baseZIndex]="10000"
> </p-confirmDialog>
Then I create service dialogue.service.ts
@Injectable({providedIn: 'root', })
export class FooService{
constructor(
private confirmationService: ConfirmationService,`
) {}
doSomeStuff() {
this.confirmationService.confirm({
key:'mainDialog',
message: 'some message',
header: 'Warning',
icon: 'pi pi-exclamation-triangle',
acceptLabel: 'ok',
rejectVisible: false,
accept: () => {},
});
}
} `
–> But this does not working . Please Am i missing something ?
I would be grateful for Your response
Solution
Ok. So the first problem is that you’re using key
as a directive (so [key]
). It means that inside you’ve to write a property declared in the component. In this case you can use directly a string, so change your HTML in this way:
<p-confirmDialog key="mainDialog" class="styleDialog" [baseZIndex]="10000">
Content
</p-confirmDialog>
Then, in you app.module.ts
you should add as provider the ConfirmationService
:
@NgModule({
declarations: [
AppComponent,
...
],
imports: [
...
ConfirmDialogModule
],
providers: [ConfirmationService],
bootstrap: [AppComponent]
})
Lastly, I noticed that’s an error in your FooService
. I suppose it’s related to your copy/paste on StackOverflow but yeah let me write it down too.
import {Injectable} from '@angular/core';
import {ConfirmationService} from 'primeng/api';
@Injectable({
providedIn: 'root'
})
export class FooService {
constructor(private confirmationService: ConfirmationService) {
}
confirm(): void {
this.confirmationService.confirm({
key: 'mainDialog',
message: 'some message',
header: 'Warning',
icon: 'pi pi-exclamation-triangle',
acceptLabel: 'ok',
rejectVisible: false,
accept: () => {
console.log('accept');
},
});
}
}
Don’t forget to declare and call you FooService.confirm
method where you need it. Let’s suppose you need it in the app.component.ts
, you’ll have something like this:
import {Component, OnInit} from '@angular/core';
import {FooService} from './foo.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
constructor(private fooService: FooService) {
}
ngOnInit(): void {
this.fooService.confirm();
}
}