NgClass doesn't work if it depends on a variable which change from an Angular Material Dialog

Discussão em 'Angular' iniciado por Rosario Di Mari, Agosto 6, 2025.

  1. Good evening. I have an Angular 17 component which class depends on a variable. Clicking 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 defined isCardOpen setting its initial value as false

    public isCardOpen:boolean = false


    3). I defined in the same class also some 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.titolo, testo: this.modalCardsList.testo, immagine: this.modalCardsList.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:

    • The functions closeCard and toggleCard work correctly and cause the correct class changes in my component when I invoke them inside the component itself
    • When I invoke it from the dialog, on closing it, the state of this.isClassOpen does not preserve the value that it had before opening the dialog: it is undefined. When closeCard() is invoked its value is set to false but this not causes any class changing on my component. I have also tried to put its value previously as "true" and immediately later to "false", but the class of my component still does not change. I remark that the function closeCard is effectively called (i see the console log inside closeCard method) and the variable this.isClassOpen changes its value, but this does not change the class of my component. The class of my component instead changes when I invoke it from something inside the component itself.

    Thanks for your help. I am interested also in understanding the motive of this behaviour and to find a solution for this issue.

    Continue reading...

Compartilhe esta Página