*ngIf and *ngFor on same element causing error in angular 12
I’m developing the angular web application and I’m trying to use the *ngIf and *ngFor on same div element but it is giving me error
@Component({ selector: 'app-error', template: ` <h3>Error Occured</h3><button (click)="toggle()">Toggle!</button> <div *ngIf="show" *ngFor="let item of errors"> {{consoleLog(item)}} <span>{{item.name}}</span> </div> ` }) export class ErrorComponent implements OnInit { public errors: any[] = []; public show: boolean = false; constructor() {} ngOnInit() { this.errors = [ { name: 'Error 1', id: 1 }, { name: 'Error 2', id: 2 } ] } toggle() { this.show = !this.show; } consoleLog(thing) { console.log(thing); } }
It can be done easily with the help of taking 1 parent div and wrapping the errors html inside it but it will add extra element in the DOM. So is there any other workaround to accomplish it ?
Add comment
Answers (1)
Add Answeryes, it’s possible. you can use the <ng-container>
element as a workaround, as it allows you to use different elements for each structural directive while not being stamped on the DOM.
<ng-container *ngIf="show"> <div *ngFor="let item of errors"> {{console.Log(item)}} <span>{{item.name}}</span> </div> </ng-container>
<ng-template> (<template> prior to Angular v4) allows you to perform the same thing, but with a convoluted syntax that is no longer encouraged.
<ng-template [ngIf]="show"> <div *ngFor="let item of errors"> {{console.Log(item)}} <span>{{item.name}}</span> </div> </ng-template>