简体   繁体   中英

How to fix ngFor/ngIf else doesn't work in angular

here's the code:

<div *ngFor="let app of application$ | async;">
  <div *ngIf="app.length > 0; else noResults">
    <li>{{app.id}}</li>
  </div>

  <ng-template #noResults>
    No Results
  </ng-template>
</div>

TS

application$ = new BehaviorSubject([]);

  constructor() { }

  ngOnInit() {
    const arr = new Array();
    const data = [{
      id: 'room1',
      name: 'Room 1'
    },{
      id: 'room2',
      name: 'Room 2'
    },{
      id: 'room3',
      name: 'Room 3'
    }];

    this.application$.next(data);

  }

how to fix the else on ngFor, it when there's no data it doesn't go in noResults. I also tried this.

HTML

<div *ngIf="application$ | async as app">
  <div *ngIf="app.length !== 0; else noResults">
    <div *ngFor="let data of app;let i = index;">
      {{ data.name }}
    </div>
  </div>
  <ng-template #noResults>
    No Results
  </ng-template>
</div>

it same error it doesn't display the noReuslts when there's no data

Your HTML should look like this

<div *ngFor="let app of application$ | async;">
    <li>{{app.id}}</li>
</div>
<div *ngIf="(application$ | async).length === 0">No Results</div>

Or

<div>
    <li *ngFor="let app of application$ | async;">{{app.id}}</li>
    <ng-container *ngIf="(application$ | async).length === 0">No Results</ng-container>
</div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM