2

I need to be able to pass a dynamic string using the fieldName in order to get an attribute within the item object. In order to make it easy to duplicate the issue I have given a small example. The problem is this syntax works properly with angular 12.2.5 as I checked but did not work with angular 12.0.0 or below. I can simply call a function but I know this is not good for performance. Is there an alternate way to write this syntax for older angular applications?

HTML

<p [style.background]="item?.[fieldName]">
  Some Text
</p>

ts

item =  { warn: 'yellow', success: 'green', error: 'red' };
fieldName = 'success';

Error looks like this

Parser Error: Unexpected token [, expected identifier or keyword at column 20 in [{background: item?.[fieldName]}]

1 Answer 1

4

Try to use ternary operator ?::

<p [style.background]="item[fieldName] ? item[fieldName] : ''">
  Some Text
</p>
Sign up to request clarification or add additional context in comments.

1 Comment

Welcome. Consider also upvoting and accepting my answer if it helped you.

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.