Using ngIf Structural Directive Freezes App

67 Views Asked by At

I have an angular 15 project in which If I run the following structural *If directive on an ng-component; the app freezes.

Attempting to recreate the issue in an simplified example using stackblitz, it works and does not freeze

Any ideas what the problem would be based on just the below examples. Even when my template contains only an ng-component I encounter the issue

<ng-component *ngIf="true"><h1>hello</h1></ng-component>

when I add a method just to debug I can see it is printing the console.log infinitely

<ng-component *ngIf="test()"><h1>hello</h1></ng-component> 

test() {
 console.log("world")
}

however when I place the structural directive on a non ng-component, it works fine

<h1 *ngIf="true"><hello</h1>
3

There are 3 best solutions below

1
On BEST ANSWER

ng-component is not a standard Angular directive or element. so structural directives do not work on it.

Needed to use an element that is recognised by Angular

0
On

You probably didn't add your component to the app.module.

Also using methods in templates is not a common practice because of the Angular's change detection mechanism resulting console.log() being displayed multiple times and doing that on each change.

1
On

You should return something out of your test function

test() {
      console.log("world");
      return true;
    }

In your case, the test() function does not return anything, thus resulting in freezing the app as it keeps on expecting a return value.

You can also maintain a variable and change it in the TS file accordingly.

test() {
  console.log("world");
  this.myVariable = true;
}

and then you can use:

<ng-component *ngIf="myVariable"><h1>hello</h1></ng-component>