首页 > 解决方案 > 以角度添加动态添加的字段值以及表单值

问题描述

我有一个名为 的组件demo,它作为一些 i/p 字段:
名字、姓氏、数字.... 连同这些字段,我动态添加了 2 个字段(即添加多个地址)。

我能够发送所有表单字段值,但不能发送动态添加的值

记录动态添加的字段值时显示为undefined. 由于组件的代码很长,我发布了 stackblitz DEMO

标签: angulartypescriptangular6

解决方案


由于地址类型是数组,您将无法轻松获得它,

  addFieldValue() {
   if (this.newAttribute.adr && this.newAttribute.city) {
     if (this.fieldArray.indexOf(this.newAttribute) === -1) {
    this.fieldArray.push(this.newAttribute)
    }
  }

   this.newAttribute = {};//see here
  }

在这里,您实际上是在清空值,因此值将始终为 0。

但是您已经将值放在 fieldArray 中,您可以通过迭代它并获取值来轻松检索数组值。

  public onAdd(): void {
    this.someContact = this.addForm.value;
    this.someContact.phoneNumbers = [];
    const phno: IPhoneNumber = {
      countryCode: this.addForm.value.counrtycode,
      number: this.addForm.value.phonenumber,
    };
    this.someContact.phoneNumbers.push(phno);

    this.someContact.addresses = [];
    this.fieldArray.forEach(a => {
      const addr: IPostalAddress = {
        addtype: a.adr,
        city: a.city,
      };
      this.someContact.addresses.push(addr);
    })


    console.log(this.someContact);
  }

我改为typeaddtype看起来不好命名。

export interface IPostalAddress {
  addtype:            string;
  city:            string;
}

演示

注意:由于您不处理可以删除的表格formControlName="adrType"


推荐阅读