Can’t have multiple template bindings on one element. use only one attribute prefixed with *

One common mistake when working with Angular template bindings is trying to use multiple template bindings on a single element. This is not allowed, and only one attribute prefixed with “*” is allowed on each element.

To demonstrate this, let’s consider an example where we have an element with two template bindings:

    <div [ngIf]="condition" *ngFor="let item of items">...</div>
  

In this example, we have both the “ngIf” and “ngFor” attributes used together on the same element. However, this code will result in an error because multiple template bindings are not allowed on one element.

To resolve this issue, we need to refactor the code and separate the template bindings into different elements or use a single “ng-template” element to hold multiple template bindings. Here’s an example of refactored code using separate elements:

    <div *ngIf="condition">
      <div *ngFor="let item of items">...</div>
    </div>
  

In this refactored version, we have a separate “ngIf” template binding and a nested “ngFor” template binding in different elements, which resolves the issue of having multiple template bindings on one element.

Another approach is to use a single “ng-template” element to hold multiple template bindings. Here’s an example:

    <ng-template [ngIf]="condition" [ngForOf]="items">
      <div>...</div>
    </ng-template>
  

In this version, we use a single “ng-template” element to hold both the “ngIf” and “ngFor” template bindings. This is a useful approach when dealing with more complex templates or when we want to reuse the template in multiple places.

So to summarize, when encountering the error “can’t have multiple template bindings on one element. use only one attribute prefixed with *”, you need to make sure that each element has only one template binding prefixed with “*”, either by separating them into different elements or by using a single “ng-template” element to hold multiple template bindings.

Similar post

Leave a comment