Reputation: 15044
Below is my partial angular2 component template html. "searchTickets$" is an Observable of array of objects.
<table class="table table-condensed" *ngIf="searchTickets$">
<thead>
<tr>
<th><h3>Ticket ID</h3></th>
</tr>
</thead>
<tbody>
<tr *ngFor="let ticket of searchTickets$ | async">
<td><small>{{ticket.ticketID}}</small></td>
</tr>
</tbody>
</table>
My intention is that the table should be displayed only when the observable returns 1 or more records.
What needs to be modfied in *ngIf condition to make that happen.
Upvotes: 1
Views: 151
Reputation: 23793
As @xe4me said :
<table class="table table-condensed" *ngIf="(searchTickets$ | async)?.length">
Should work.
BUT
Don't forget that async is subscribing to your observable.
Which means that having :
<table class="table table-condensed" *ngIf="searchTickets$">
and
<tr *ngFor="let ticket of searchTickets$ | async">
Will lead to two different subscriptions.
If you're making an HTTP call somewhere in your observable chain, it'll be fired twice.
This is not a really good option here I guess.
Instead, you should be doing something like that :
if you want to handle the observable from your HTML without firing your observable multiple times due to async
@Component({
...
})
export class YourComponent {
public searchTickets: any;
constructor(private yourService: any) {
this.searchTickets = yourService
.getSearchTicket()
.share();
// share allows you to avoid duplicate subscriptions
}
}
if you want to handle the observable from your TS
@Component({
...
})
export class YourComponent implements OnDestroy {
public searchTickets: any;
private searchTicketsSub: Subscription;
constructor(private yourService: any) {
this.searchTickets =
// let say you have the observable coming from a service that
// makes an HTTP call
yourService
.getSearchTicket()
.subscribe((searchTickets: any) => this.searchTickets = searchTickets);
}
ngOnDestroy() {
// then, don't forget to unsubscribe
this.userSub.unsubscribe();
}
}
Upvotes: 2
Reputation: 6974
You should try
<table class="table table-condensed" *ngIf="(searchTickets$ | async)?.length > 0">
Upvotes: 0