![](/img/trans.png)
[英]Angular4: Recovering one-way data binding value on input after resetting the form
[英]one-way binding to input not displaying value
我正在嘗試將組件的 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;
}
當我在瀏覽器中打開頁面時,我可以看到以下內容:
但我的輸入都不包含“找到一個值”:
問題是我使用的是 forEach function 並且沒有從中返回值
將代碼更新為常規 foreach 解決了該問題:
getStepParameterValue(parameter: UIParameter, testCaseStep:TestCaseStep) {
for (let stepParameter of testCaseStep.Parameters) {
if (stepParameter.UIOperationParameterName === parameter.UIOperationParameterName)
{
return stepParameter.ParameterValue;
}
};
return null;
}
我知道你已經回答了你的問題,但是你的代碼可以這樣寫:
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;
}
另一方面,在模板中綁定 function 調用不是一個好主意。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.