one-way binding to input not displaying value

Viewed 28

I'm trying to bind the value of an input (inside a foreach loop) in the Html part of my component to a function:

<input [ngModel]="getStepParameterValue(parameter, testCaseStep)" required />

...

  // Get the previously saved value for this parameter
  getStepParameterValue(parameter: UIParameter, testCaseStep:TestCaseStep) {
    testCaseStep.Parameters.forEach((stepParameter: Parameter) => {
      if (stepParameter.UIOperationParameterName === parameter.UIOperationParameterName)
      {
        if (stepParameter.ParameterValue == null)
        {
          return null;
        }
        console.log("Found value");
        return "Found a Value";
      }
    });

    // A value for this parameter was not found
    return null;
  }

When I open the page in a browser, I can see the following:

enter image description here

But none of my inputs contain "Found a Value":

enter image description here

2 Answers

The problem was that I was using the forEach function and not returning a value from it

Updated code to a regular foreach addressed the issue:

  getStepParameterValue(parameter: UIParameter, testCaseStep:TestCaseStep) {
    for (let stepParameter of testCaseStep.Parameters) {
      if (stepParameter.UIOperationParameterName === parameter.UIOperationParameterName)
      {
        return stepParameter.ParameterValue;
      }
    };
    return null;
  }

I know that you've answered your question, but your code can be written like this:

getStepParameterValue(parameter: UIParameter, testCaseStep:TestCaseStep) {
   const result = testCaseStep.Parameters.find(
      (p) => p.UIOperationParameterName === parameter.UIOperationParameterName
   );
   return result?.ParameterValue; 
   // or if you strictly want null, result?.ParameterValue ?? null;
}

On another note, binding a function call in your template is not a good idea.

Related