Home > other >  How to build up a json value within angular template
How to build up a json value within angular template

Time:11-03

I have such element within my template:

value="{{option.id}}"

I want to turn the param value into a json object using template literals

value="{{`id: ${option.id}, field: ${otherParam}`}}" 

So the value would looks like { id: 'bla', field: 'other' }, is it possible to do that?

I also tried {{ JSON.parse(....)} } by creating a component variable JSON = JSON but still having difficulties using template literals.

CodePudding user response:

There is JSON.stringify(yourObject)

see documentation here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify

CodePudding user response:

Yes, it is possible. But you should not pass a string to value attribute in your case. Instead bind to value using [] in order to bind custom objects:

[value]="{id: option.id, field: otherParam}" 

Note: You can use any variables you like in this binding, which are available in this context. This can be either other HTML tags (referenced by #), public variables from your component or dynamically defined ones (like variables defined in parent *ngFor directive).

  • Related