为什么通过 [(ngModel)] 初始化的组件变量仍然有空值?

问题描述

我正在开发一个 Angular 应用程序,但遇到以下问题。

我在反应式中定义了这两个字段:

<div class="row">
  <div class="col-2">
    <p>Prezzo fattura</p>
  </div>
  <div class="col-10">
    <p-inputNumber id="invoice_cost" formControlName="invoice_cost"  [(ngModel)]="invoiceCostNg"
                   mode="currency" currency="EUR" locale="de-DE"
                   [disabled]="!isEditAssetDetails">
    </p-inputNumber>
      
  </div>
</div>

<div class="row">
  <div class="col-2">
    <p>Franchigia</p>
  </div>
  <div class="col-10">
    <p-inputNumber id="deductible" formControlName="deductible" [(ngModel)]="deductibleNg"
                   mode="currency" currency="EUR" locale="de-DE"
                   [disabled]="!isEditAssetDetails"
                   (onInput)="calculateDeprecation($event)">
    </p-inputNumber>                         
  </div>
</div>

如您所见,这两个表单字段都将 [(ngModel)] 链接到以下 TypeScript 组件代码变量 invoiceCostNgdeductibleNg

在我的 TypeScript 组件代码中,我做了这样的事情:

@Component({
  selector: 'app-asset-details',templateUrl: './asset-details.component.html',styleUrls: ['./asset-details.component.scss']
})
export class AssetDetailsComponent implements OnInit {

    ................................................................
    ................................................................
    ................................................................
    invoiceCostNg: number = null;
    deductibleNg: number = null;
    ................................................................
    ................................................................
    ................................................................
    
    public calculateDeprecation(value) {

        let startingValue = this.assetDetailsForm.value.invoice_cost;
        let deductible = this.assetDetailsForm.value.deductible;

        console.log("INVOICE COST: ",this.invoiceCostNg);
        console.log("DEDUCTIBLE: ",this.deductibleNg);
    }
}

如您所见,将值更改为第二个输入字段,这称为 calculateDeprecation() 方法,该方法必须同时使用 this.invoiceCostNg 和 this.deductibleNg 字段(通过 [(ngModel)] 属性限定的字段)。

问题在于,当这个方法被执行时,这是在 Chrome 控制台中获得的输出

INVOICE COST:  null      asset-details.component.ts:432 
DEDUCTIBLE:    null      asset-details.component.ts:432 

在我看来,[(ngModel)] 属性基本上没有填充相关的组件变量。

为什么?怎么了?我错过了什么?我该如何尝试解决此问题?

解决方法

  1. 您可以使用 (ngModelChange) 检查 ngModel 发出的值
  2. 我认为问题来自输出(onInput)
  • 同1,可以使用(ngModelChange)来处理事件deductibleNg变化
  • 使用反应式形式
FormGroup.get('deductible').valueChanges.subscribe((val) => {
// handle logic here
})
,

定义如下: invoiceCostNg:任何; deductibleNg:任何; 默认情况下,angular 将变量初始值视为“未定义”。 在这里,您已将默认值定义为 null,这就是您在控制台中获取 null 的原因。 为什么你同时使用了 ngModel 和 formControlName?