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:
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
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 .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.