Search code examples
angulartypescriptdialogcomponents

Unnecessary multiple method call upon displaying angular modal dialog


In my angular (version 9) project I have a component that represents a modal dialog. In the component template there is the following line of code, that is responsible for the dialog title representation.

<p mat-dialog-title>{{ generateDialogTitle() }}</p>

In the component typescript file, there is a method generateDialogTitle():string that returns generated dialog title (it depends on the dialog data).

The modal dialog is being called via code and this code is being called once when I click on a button.

var dialogRef = this.dialog.open(QuestionDetailsComponent, dialogConfig);
dialogRef.afterClosed().subscribe(result => {
  if (result) {
    // if dialog has been accepted
    ... some code here
  }
});

What is strange, upon displaying the modal dialog, the method generateDialogTitle() is being called multiple times when it is being used in the component template (it is the only place where it is being used).

It somehow called implicitly multiple times and I don't understand why.

I noticed it in the console upon debugging.

Then I removed binding to generateDialogTitle() method from the template, added new property dialogTitle to the class, and the dialog title looked like that:

<p mat-dialog-title>{{ dialogTitle }}</p>

I marked generateDialogTitle() as private method and called it explicitly in the constructor, to assign its value to dialogTitle property.

And in this case it called only once.

I don't understand, why this method when it is used directly in html-template is being called (implicitly) multiple times. Why does it happen? Is it normal behavior?


Solution

  • According to the @ritaj comments, it is the expected Angular behavior.

    Angular calls functions called from template on every change detection run.

    It is better to use properties instead of methods in your html-templates. Explicitly assign your properties and bind them to the html-template parts.