无法在 Angular 中使用 Formbuilder 在 select 元素中设置数组值

Can't set array values in select elements using Formbuilder in Angular

我有这个编辑功能。只有 select 元素不更新值

发票-update.component.ts

onUpdate(invoice) {
 console.log(invoice.customer)

 const control = <FormArray>this.form.controls['purchases'];
 control.controls = [];

 this.form.controls['$key'].setValue(invoice.$key);
 this.form.controls['customer'].setValue(invoice.customer);//this is the problem

 for (let i in invoice.purchases) {
   const product = (invoice.purchases[i].product);
   const quantity = (invoice.purchases[i].quantity);
   this.addPurchase(product);
   control.at(+i).get('quantity').setValue(quantity);
 }
}

虽然值是在 select 元素中设置的,但它不允许更新值,因为它需要一个数组

Stackblitz

它没有更新,因为您的发票模型接受客户对象,但您只传递了一个名称。

export class IInvoice {
  $key?: string;
  invoiceNumber?: number;
  createdAt?: string;
  modifiedAt?:string;
  uid?: string;

  customer: Customer; // Currently you are passing string to this key.
  purchases: Purchase[];
  totalPrice: number;
}

按项目替换item.name。 从这里更新您的 select 代码:

 <select class="form-control custom-select" id="customer" formControlName="customer">
         <option [ngValue]="true">-Customer-</option>

         <option [ngValue]="item.name" *ngFor="let item of customerList" >{{item.name}} {{item.lastname}}</option>
 </select>

对此:

 <select class="form-control custom-select" id="customer" formControlName="customer">
         <option [ngValue]="true">-Customer-</option>

         <option [ngValue]="item" *ngFor="let item of customerList" >{{item.name}} {{item.lastname}}</option>
 </select>

然后就可以了。

要将 selected 客户设置为下拉列表中的默认值,您可以使用 compareWith 属性。这个 属性 接受函数参数。只需在 select 标签中添加以下 属性:-

[compareWith]="compareFn"

并像这样定义compareFn函数:-

compareFn(c1: any, c2:any): boolean {
   return c1 && c2 ? c1.name === c2.name : c1 === c2;
} 

现在应该根据 selected 数据按预期设置默认客户。