You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular 4中对象为null时输入控件显示0的实现方案求助

Simplify Your Angular 4 Input Display for Unselected Dropdown

Hey there, let’s tackle this problem and clean up your code at the same time. Your current approach uses two duplicate input components (one for when fedExTax exists, one for when it doesn’t) which creates unnecessary redundancy. Plus that "Cannot read property 'reduce' of undefined" error is likely popping up because you’re accessing properties on an undefined value somewhere—let’s fix both issues.

Option 1: Adjust the Getter to Return a Default Object (Cleanest Approach)

Instead of returning null when no dropdown option is selected, return a fallback FedExciseExpense object with value: 0. This lets you use a single input component in your template, since fedExTax will always exist (either the matched item or the default).

Update your component code:

get fedExTax(): BackendDto.FedExciseExpense {
  // First, make sure our array exists to avoid undefined errors
  if (this.currentSelectedCoveragePolicy !== 0 && this.fedExciseExpensesInputs) {
    const matchedExpense = this.fedExciseExpensesInputs.find(
      x => x.coveragePolicyTypeId === this.currentSelectedCoveragePolicy && x.is953D === this.currentSelected953D
    );
    // Return the matched item, or a default object with value 0
    return matchedExpense || ({ value: 0 } as BackendDto.FedExciseExpense);
  }
  // Return default when no coverage policy is selected
  return { value: 0 } as BackendDto.FedExciseExpense;
}

Now simplify your template to just one input block (no more *ngIf toggling):

<div class="col-lg-3 col-6 mb-3">
  <label class="col-form-label">{{'CAPTIVES.LINES.INCCAPTIVEEXPENSE.' + FedExciseKey|uppercase|translate}}</label>
  <div class="input-group">
    <input type="text" 
           class="form-control form-control-sm" 
           [(ngModel)]="fedExTax.value" 
           [ngModelOptions]="{standalone: true}" 
           name="{{FedExciseKey}}" 
           numberFormat="numberPercent:.0-2" 
           (ngModelChange)="change()" 
           [required]="true" 
           tooltip="{{'CAPTIVES.LINES.INCCAPTIVEEXPENSE.' + FedExciseKey + 'TOOLTIP'|uppercase|translate}}" 
           placement="bottom">
    <span class="input-group-addon">%</span>
  </div>
</div>

Why This Fixes the "reduce" Error

That error was probably happening because fedExciseExpensesInputs was undefined when your getter tried to call .find() on it, or your numberFormat pipe was trying to run reduce on an undefined value. Adding the check for this.fedExciseExpensesInputs ensures we only call .find() if the array exists, and the default object guarantees value is never undefined.

Option 2: Template-Only Adjustment (If You Don’t Want to Modify the Getter)

If you prefer keeping the getter as-is, you can use a ternary operator in the ngModel binding and handle updates in a custom change handler:

Template:

<div class="col-lg-3 col-6 mb-3">
  <label class="col-form-label">{{'CAPTIVES.LINES.INCCAPTIVEEXPENSE.' + FedExciseKey|uppercase|translate}}</label>
  <div class="input-group">
    <input type="text" 
           class="form-control form-control-sm" 
           [(ngModel)]="fedExTax ? fedExTax.value : 0" 
           [ngModelOptions]="{standalone: true}" 
           name="{{FedExciseKey}}" 
           numberFormat="numberPercent:.0-2" 
           (ngModelChange)="handleValueChange($event)" 
           [required]="true" 
           tooltip="{{'CAPTIVES.LINES.INCCAPTIVEEXPENSE.' + FedExciseKey + 'TOOLTIP'|uppercase|translate}}" 
           placement="bottom">
    <span class="input-group-addon">%</span>
  </div>
</div>

Component change handler:

handleValueChange(newValue: number) {
  if (this.fedExTax) {
    this.fedExTax.value = newValue;
    this.change(); // Call your existing change logic
  } else {
    // Optional: Create a new expense object if you need to save this 0 value
    // const newExpense: BackendDto.FedExciseExpense = {
    //   coveragePolicyTypeId: this.currentSelectedCoveragePolicy,
    //   is953D: this.currentSelected953D,
    //   value: newValue
    // };
    // this.fedExciseExpensesInputs.push(newExpense);
  }
}

Either approach will eliminate the duplicate code and ensure your input shows 0 when no dropdown option is selected. The first option is my recommendation since it keeps your template clean and centralizes the fallback logic in the component.

内容的提问来源于stack exchange,提问作者Tom

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 07:03:11