2

I would like to avoid to use .subscribe() in this component. I tried *ngIf="user$ | async as user" but it did not work.

How can I make a local variable with user$ | async un order to use it at different places in this view?

<app-xpbar *ngIf="user$ | async"></app-xpbar>

<header class="header">

  <app-header-common
    (onSearch)="searching($event)">
  </app-header-common>

  <app-header-user
    [user]="user$ | async"
    (onLogin)="login($event)"
    (onTrial)="trial($event)">
  </app-header-user>

</header>
Tom
  • 785
  • 10
  • 26

3 Answers3

3

Update

As @yurzui pointed out, this only works if the references to the introduced variable user are within the <pp-xpbar> element where it's introduced. Otherwise the variable won't be in scope (like in the code example below)

Original

In Angular4 you can use

<app-xpbar *ngIf="user$ | async; let user"></app-xpbar>

<header class="header">

  <app-header-common
    (onSearch)="searching($event)">
  </app-header-common>

  <app-header-user
    [user]="user"
    (onLogin)="login($event)"
    (onTrial)="trial($event)">
  </app-header-user>

</header>

See also

For the as syntax mentioned in the comments see

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
2

You can try to create structural directive like:

ng-async.directive.ts

@Directive({ selector: '[ngAsync]' })
export class NgAsync {
   constructor(private vcRef: ViewContainerRef, private templateRef: TemplateRef<any>) {}

   @Input()
   set ngAsync(variable: any) {
      this.vcRef.clear();
      this.vcRef.createEmbeddedView(this.templateRef, { $implicit: variable });
   }
}

Then you can use it the following way

view.html

<ng-container *ngAsync="user$ | async; let user">
  <app-xpbar *ngIf="user"></app-xpbar>

  <header class="header">

    <app-header-common
      (onSearch)="searching($event)">
    </app-header-common>

    <app-header-user
      [user]="user"
      (onLogin)="login($event)"
      (onTrial)="trial($event)">
    </app-header-user>

  </header>
</ng-container>
yurzui
  • 205,937
  • 32
  • 433
  • 399
0

After thinking of pros and cons of differents propositions, I'll go with a ParentComponent event if it's here only for getting user stream. Thanks everyone.

Tom
  • 785
  • 10
  • 26