1

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:

  • 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

1 Answer 1

2

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>
Sign up to request clarification or add additional context in comments.

2 Comments

Exactly, thank you very much, only one bracket was missing: {{$any(a)[attribute]}}
{{obj[attribute]}} is also working if attribute is a variable containing key name. Example: attribute = 'name' then it will populate value of obj.name where name is field in object 'obj'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.