TypeError:无法读取未定义的属性“length”

时间:2018-03-13 11:16:56

标签: angular forms typescript

我想将unit_price *数量与一个函数相加但显示此错误。

我的代码ts:

 products: Products[];
    this.myForm = this.fb.group({
      'Quantity': new FormControl('', Validators.required),
      'Unit_price': new FormControl('', Validators.required),
      'Subtotal': new FormControl(this.Subtotal(), Validators.required),

    });

 Subtotal() {
   let subtotal = 0;
     for (let p of this.products) {
      subtotal = p.Unit_price * p.Quantity;
     }
     return subtotal;
   }

html代码

<form [formGroup]="myForm">

    <div class="input-field col s12">
      <input formControlName="Quantity" id="Quantity " type="number" class="validate" [(ngModel)]="Quantity">
    </div>
    <div class="input-field col s12">
      <input formControlName="Unit_price" id="Unit_price" type="number" class="validate" [(ngModel)]="Unit_price">
    </div>
    <div class="input-field col s12">
     <div class="c1" style="text-align:left;">
      Subtotal:
      <label for="total">Total {{Subtotal}} ALL</label>
       <input formControlName="Subtotal" id="Subtotal" type="number" class="validate" [value]="Subtotal"> 
    </div>
  </div>
</form>
你能帮帮我吗?我是新的网络程序员。

谢谢

1 个答案:

答案 0 :(得分:0)

发生这种情况是因为你没有初始化产品数组

试试这个 products: Products[] = [];