*ngIf and *ngFor on same element causing error in angular 12

Forums Angular*ngIf and *ngFor on same element causing error in angular 12
Staff asked 2 years ago

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

  selector: 'app-error',
  template: `
    <h3>Error Occured</h3><button (click)="toggle()">Toggle!</button>

    <div *ngIf="show" *ngFor="let item of errors">

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) {


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 ?

Answers (1)

Add Answer
Staff answered 2 years ago

yes, 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">

<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">




Select Categories