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
- Undefined symbols for architecture x86_64: “_main”, referenced from: implicit entry/start for main executable ld: symbol(s) not found for architecture x86_64 clang: error: linker command failed with exit code 1 (use -v to see invocation)
- Docker: error response from daemon: failed to create task for container: failed to create shim task: oci runtime create failed: runc create failed: unable to start container process: exec: “uvicorn”: executable file not found in $path: unknown.
- Typeerror: bar() missing 1 required positional argument: ‘height’
- Can’t add new command when connection is in closed state