Search code examples
angularangular-pipe

How to store ` keyvalue` in the template variable


I am trying to use the keyvalue and print in template. but not able to assign with variable. what would be the correct approach here?

<h1 let item = (data|keyvalue)>New value {{item.key}}</h1> - not working

in my ts file there is a data:

data = { value: 'info' };

I can directly print this. but to know how it can be handled with keyvalue

Thanks in advance.


Solution

  • The keyvalue pipe return an array of key-value-pairs. Only in your example the object has a single entry. Either iterate the resulting array with *ngFor or access the first array element like below.

    <h1 *ngIf="(data | keyvalue)?.[0] as item">
      New value {{ item.key }}
    </h1>