无法使用Angular中的Formbuilder在选择元素中设置数组值

时间:2019-04-18 17:17:59

标签: angular formbuilder formarray

我具有此编辑功能。只有select元素不会更新值

invoice-update.component.ts

<div class="wrapper1">

  <div>
    <p class="item1">SHIPPED for free | GUARANTEED TO LAST</p>
  </div>


  <div>
    <p class="item2">LOG IN | REGISTER | CUSTOMER SERVICE | 1-800-692-8259 </p>
  </div>

</div>

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

Stackblitz

1 个答案:

答案 0 :(得分:1)

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

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 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>

然后它将起作用。

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

[compareWith]="compareFn"

并定义 compareFn 函数,如下所示:-

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

现在应根据所选数据将默认客户设置为预期客户。