Reputation: 128
I would like to use a string "attribute" as a key to access the value of a field in the "anim.animals" object.
"anim" is an object of type Response that contains among other things the string "attribute" and an array "animals" of type animal.
(you can beat me up later for naming classes and variables ahah)
As you can see from the piece of code I'm iterating through the array to access the animals parameters, one of which is identified by the string "attribute".
<div class="col-sm" *ngFor="let a of anim.animals">
<a>{{a.name}}</a><br>
<a *ngIf="feedback == 'Wrong'">{{a[attribute as keyof typeof animal]}}</a>
</div>
Both trying to access it with the dot and in this reported way (which I found on the internet and don't know well yet), errors appear:
Do you have any idea how I can solve the problem (without disrupting everything maybe)? Thanks
Upvotes: 1
Views: 1502
Reputation: 10979
If attribute is the key name
<div class="col-sm" *ngFor="let a of anim.animals">
<a>{{a.name}}</a><br>
<a *ngIf="feedback == 'Wrong'">{{$any(a).attribute}}</a>
</div>
or
<div class="col-sm" *ngFor="let a of anim.animals">
<a>{{a.name}}</a><br>
<a *ngIf="feedback == 'Wrong'">{{a['attribute']}</a>
</div>
If attribute is a variable containing keyname
<div class="col-sm" *ngFor="let a of anim.animals">
<a>{{a.name}}</a><br>
<a *ngIf="feedback == 'Wrong'">{{$any(a)[attribute]}</a>
</div>
Upvotes: 2