简体   繁体   English

单向绑定输入不显示值

[英]one-way binding to input not displaying value

I'm trying to bind the value of an input (inside a foreach loop) in the Html part of my component to a function:我正在尝试将组件的 Html 部分中的输入值(在 foreach 循环内)绑定到 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:当我在浏览器中打开页面时,我可以看到以下内容:

在此处输入图像描述

But none of my inputs contain "Found a Value":但我的输入都不包含“找到一个值”:

在此处输入图像描述

The problem was that I was using the forEach function and not returning a value from it问题是我使用的是 forEach function 并且没有从中返回值

Updated code to a regular foreach addressed the issue:将代码更新为常规 foreach 解决了该问题:

  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 .另一方面,在模板中绑定 function 调用不是一个好主意

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM