首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >无法在Angular中使用Formbuilder设置选择元素中的数组值

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

Stack Overflow用户
提问于 2019-04-19 01:17:59
回答 1查看 56关注 0票数 0

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

invoice-update.component.ts

代码语言:javascript
复制
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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-04-19 02:12:33

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

代码语言:javascript
复制
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代码:

代码语言:javascript
复制
 <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>

要这样做:

代码语言:javascript
复制
 <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标签中添加以下属性:

代码语言:javascript
复制
[compareWith]="compareFn"

并像这样定义compareFn函数:

代码语言:javascript
复制
compareFn(c1: any, c2:any): boolean {
   return c1 && c2 ? c1.name === c2.name : c1 === c2;
} 

现在,应根据所选数据设置默认客户。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55750923

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档