Good evening.
I have an Angular 17 component which class depends on a variable. Clicking on it an Angular Material dialog opens. The task is to change the class of my component when I close the dialog.
To achieve this goal, I have made the following.
1). I binded NgClass
of my component to a boolean variable:
<div [ngClass]="(!isCardOpen)? 'card_whyMeClosed' + $index : 'card_whyMeOpen' + $index
2). In my component I have defined isCardOpen
setting its initial value to false
.
public isCardOpen:boolean = false
3). I defined in the same class the functions to open and close the card.
closeCard(): void{
this.isCardOpen=false;
console.log("Close card invoked", this.isCardOpen);
}
toggleCard(): void{
console.log("Toggle card invoked");
this.isCardOpen=!this.isCardOpen;
}
4). When I open the dialog, I pass as parameter the function this.closeCard
defined above.
const dialogRef = this.dialog.open(ModalCardDialog, {
width: "500px",
panelClass: 'my-dialog',
data: {
titolo: this.modalCardsList[i].titolo,
testo: this.modalCardsList[i].testo,
immagine: this.modalCardsList[i].immagine,
closeCard: this.closeCard
},
5). In the end, I invoke closeCard
in the ts which defines the dialog, in the function which is invoked when the modal is being closed.
onNoClick(): void {
this.data.closeCard && this.data.closeCard();
console.log("Chiudi modale");
this.dialogRef.close();
}
Results:
Thanks for your help. I am interested also in understanding the motive of this behaviour and to find a solution for this issue.
When you pass the function as a parameter to the dialog function, you need to also specify the scope (context) where the function should be executed on.
The problem with your method is that, you are passing the function expecting the function to be executed on the parent component context (Component that opens the dialog). But the function is called inside the dialog component (So it will be executing on the dialog component context). So in the dialog component a property isCardOpen
is created which is of no use.
The define the scope on which the function is executed we use .bind(this)
. This ensures wherever the function is called, the scope will always be the parent component context (Component that opens the dialog).
const dialogRef = this.dialog.open(ModalCardDialog, {
width: "500px",
panelClass: 'my-dialog',
data: {
titolo: this.modalCardsList[i].titolo,
testo: this.modalCardsList[i].testo,
immagine: this.modalCardsList[i].immagine,
closeCard: this.closeCard.bind(this), // <- changed here!
},