0

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
  • the issue is not the async pipe, is the expression logic you are writing in the template HTML, it should be in a function, try it
    – Andres2142
    Commented Jun 16, 2023 at 1:52

1 Answer 1

0

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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.