async pipe .find now allowed in Angular template?

152 Views Asked by At

Can anyone help me understand why this is not allowed in the Angular template?

    <ng-container *ngIf="pt$ | async as pt">
        <componenetOne[color]="pt.products.find(product => product.partKey === this.item.product.partKey).color.value">
        </item>
         ...
       <componentTwo[pt]=pt></componentTwo>
    </componenetOne>
    </ng-container>

It's complaining:

enter image description here

Unresolved variable or type product

I need to have 2 values available to the template:

  1. pt
  2. color that comes from {{pt.products.find(product => product.partKey === this.item.product.partKey).color.value}}

pt comes from an observable, and color comes from the desired product of the array called products that come from pt.

I need to have both because both values will be used in the template.

What's the way to do this?

1

There are 1 best solutions below

0
Ilamuhil Ilavenil On

You can use the map function from rxjs library to resolve this

//in your component.html file (if you do not have anything else you can remove the ngcontainer)

<componentOne[color]="prodColor$|async">
  </item>
   ...
  <componentTwo[pt]="pt$|async"></componentTwo>
</componenetOne>




//in your component.ts file 
import {map} from 'rxjs';


//Some other component boiler plate
export class MyComponent(){
// pt$ = your defined observable 
prodColor$ = pt$.pipe(map(products=> products.find(product => product.partKey === this.item.product.partKey).color.value))


}

The map function from rxjs will convert your observable from one that resolves to a products array to one that resolves to the desired product color

If you do not want to work with observable and find it difficult then you can use the tap operator to assign the product color to an instance of the class. Like so:

import {tap} from 'rxjs'
...
export class MyComponent(){
prodColor:string
// pt$ = your defined observable 
prodColor$ = pt$.pipe(tap(products=>{ this.prodColor =products.find(product => product.partKey === this.item.product.partKey).color.value)
})

//in your component.html file
<ng-container *ngIf="pt$ | async as pt">
<componentOne[color]="prodColor">
</item>
 ...
<componentTwo[pt]="pt"></componentTwo>
  </componentOne>
</ng-container>

Note the map operator function must return a value but that is not the case with tap.