skip to Main Content

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


  1. Chosen as BEST ANSWER

    This is the solution I finally came up with.

    .ts

    nutrients = {};
      getNutrients() {
        for (let nutrient of this.food.nutrient) {
          this.nutrients[nutrient.name] = nutrient.amount + nutrient.units;
        }
      }
    

    .html

    <td class="dv">
       <input type="text" name="Total lipid (fat)"
              value="{{nutrients['Total lipid (fat)']}}">
    </td>
    

  2. You might be able to do that using a key-value array. Something like:

    interface Foo {
       [key: string]: number;
    }
    
    
    let foo:Foo[] = [];
    foo.push({
      'totalFat': 1337
    });
    

    Then, from your template:

    <td> <input type="text" name="totalFat" value={{foo[name]}}> </td>
    

    Didn’t had a chance to run it, but give it a try.

    Login or Signup to reply.
  3. <input type="text" name="Total Fat" value="{{nutrients['Total Fat']}}">
    

    we use double quotes to enclose the entire attribute value, and single quotes to enclose the object key inside the attribute value.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search