Search code examples
angularobjectrxjssubscription

Subscribing to properties of an object with async pipe


Are there any downsides to subscribe to properties of an object this way:

    <th [attr.colspan]="(headerColSpan$ | async).aaa">...</th>
    <th [attr.colspan]="(headerColSpan$ | async).bbb" >...</th>
    <th [attr.colspan]="(headerColSpan$ | async).ccc">...</th>
    <th [attr.colspan]="(headerColSpan$ | async).ddd" >...</th>
    this.headerColSpan$ = new Observable((subscriber) => {
    subscriber.next(this.headerColspan);
    });

    this.headerColspan = {aaa: 2, bbb: 3, ccc: 1, ddd: 5};

This is how it seems to work, but I'm not sure if it's correct in the sense of how RxJS should be used.

The alternative would be to make four BehaviorSubjects. One for each colspan.

Would that be better for any reason?


Solution

  • You can use the async pipe once, and assign its result to a template variable, then use it to access the properties you need, like the following:

    <ng-container *ngIf="headerColSpan$ | async as headerColSpan">
      <th [attr.colspan]="headerColSpan.aaa">...</th>
      <th [attr.colspan]="headerColSpan.bbb">...</th>
      <th [attr.colspan]="headerColSpan.ccc">...</th>
      <th [attr.colspan]="headerColSpan.ddd">...</th>
    </ng-container>