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

Why component variables initialized via [(ngModel)] still have null values?

我正在开发 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 组件代码变量 invoiceCostNg免赔额.

在我的 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.invoiceCostNgthis.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 change
  • 使用反应形式
FormGroup.get('deductible').valueChanges.subscribe((val) => {
// handle logic here
})

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