Home > Back-end >  Angular - Access to object attribute with a string variable in property binding
Angular - Access to object attribute with a string variable in property binding

Time:05-06

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  *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:

  • error NG5002: Parser Error: Missing expected ] at column 13 in [{{a[attribute as keyof animal]}]
  • error TS7053: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'animal'. No index signature with a parameter of type 'string' was found on type 'animal

Do you have any idea how I can solve the problem (without disrupting everything maybe)? Thanks

CodePudding user response:

If attribute is the key name

<div  *ngFor="let a of anim.animals">
           <a>{{a.name}}</a><br>
           <a *ngIf="feedback == 'Wrong'">{{$any(a).attribute}}</a>
</div>

or

<div  *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  *ngFor="let a of anim.animals">
           <a>{{a.name}}</a><br>
           <a *ngIf="feedback == 'Wrong'">{{$any(a)[attribute]}</a>
</div>
  • Related