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
Answers
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
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.You should return something out of your test function
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.
and then you can use: