首页 > 解决方案 > Angular 中的模型

问题描述

我有这个模型

export class model{
  Id: string;
  Name: string;
  home: Home[];
}

export class Home{
  street: string;
  country: string;
  CP: string;
}

问题是如何在父模型中使用模型 Home 的值并使用表单中的值插入新寄存器,例如:

<form>
 <input type="text" ([ngModel])="model.id">
 <input type="text" ([ngModel])="model.Name">
 <input type="text" ([ngModel])="model.Home.CP"><!--How to implements the values of home to insert a value in the BD-->
</form>

谢谢

标签: typescriptangular4-forms

解决方案


@胡安佩雷斯

要在类中使用Home[]数组model,您需要在model类构造函数中实例化数组。然后在将数据绑定到类的home属性时model,必须在home数组中使用索引。可能的代码如下所示

<input type="text" ([ngModel])="model.home[index].CP">

model类中,构造函数应如下所示

export class model{
  Id: string;
  Name: string;
  home: Home[];

  model() {
    home = new Array(3).fill(new Home());
  }
}

export class Home{
  street: string;
  country: string;
  CP: string;

  Home() {
    street = "";
    country = "";
    CP = "";
  }
}

推荐阅读