I have an html form with an input element. I have an array of typescript values. I want to populate the value of the input field with a value from the array, depending on the name of the input field.
I have an html table input input field, like this:
<td>
<input type="text" name="totalFat" value={{totalFat}}>
</td>
In the typescript I have
totalFat = '2.5g';
This correctly displays 2.5g in the input field.
But how to get the totalFat variable from an array, instead of hard-coding it?
EDIT:
I have an array nutrientGuis: NutrientGui[]. NutrientGui is an object {name:string,amount:number}
.
Creating the nutrientGuis array is failing with "Cannot set properties of undefined (setting ‘Vitamin A, IU’)"
That is the first record in the source. Here is that record:
amount: 3360
id: 1104
name: "Vitamin A, IU"
source: "Lab"
units: "IU"
And the for loop that tries to add it to the nutrient array is:
for (let nutrientGui of this.myFoodGui.nutrientGuis) {
console.log("nutrientGui=", nutrientGui);
this.nutrientGuis[nutrientGui.name] = nutrientGui.amount;
}
What am I doing wrong?
3
Answers
This is the solution I finally came up with.
.ts
.html
You might be able to do that using a key-value array. Something like:
Then, from your template:
Didn’t had a chance to run it, but give it a try.
we use double quotes to enclose the entire attribute value, and single quotes to enclose the object key inside the attribute value.