【问题标题】:How to bind dynamic data with input fields using ngModel如何使用 ngModel 将动态数据与输入字段绑定
【发布时间】:2020-08-28 21:26:25
【问题描述】:

我有一个动态列表,其中包含一些输入和选择字段,我想通过这些字段绑定动态数据。我尝试与 ngModel 绑定,但它只显示最后一个对象的条目。这是我要绑定的数据

properties=[
   {
    "Id": "01",
    "PropertyType": null,
    "PropertyTypeId": 1,
    "PropertyName": "Name",
    "AdditionalList": []
  },
  {
    "Id": "02",
    "PropertyType": null,
    "PropertyTypeId": 1,
    "PropertyName": "Phone",
    "AdditionalList": []
  },
  {
    "Id": "03",
    "PropertyType": null,
    "PropertyTypeId": 1,
    "PropertyName": "Work Phone",
    "AdditionalList": []
  }]

预期的输出应该是这样

提前谢谢...

【问题讨论】:

  • 看看angular.io的ngFor。此外,Angular 中的强类型模型。
  • @r2018 谢谢,但你能提供一个具体的链接吗?
  • @P.Dederer 在回答中给出了它的用法示例

标签: html angular


【解决方案1】:
  propertyTypes= [
    { id: 1, name: "List" },
    { id: 2, name: "Text" },
  ];
selectedValue = null;

这是绑定所选值的方式

<select [(ngModel)]="selectedValue" (click)="showSelected()">
  <option *ngFor="let c of propertyTypes" [ngValue]="c.type">
    {{ c.type }}
  </option>
</select>

这里有一个提示,你可以如何使用 showselected 方法处理选定的对象

 showSelected(item) {
    console.log(this.selectedValue);
  }

【讨论】:

  • 好的..这是正确的,但我如何在输入字段中设置数据。
  • 我试过这个 -
  • 您正在混合反应式和模板驱动的方法。使用 [(ngModel)](模板)或 formControlName(反应式)。删除例如 formControlName 并在组件 property.PropertyName 中添加属性。而已。您已经将 PropertyName 设置为输入的值
  • 谢谢,@P.Dederer 我找到了解决方案。我使用 formControlName 绑定数据,并像这样从组件中设置值 getFormGroupForUserProperty(userProperty: any): FormGroup { return new FormGroup({ propertyName: new FormControl(userProperty.PropertyName), propertyType: new FormControl(userProperty.PropertyTypeId) , parentProperty: new FormControl(userProperty.ParentHierarchyPropertyId), readOnly: new FormControl(userProperty.IsReadOnly) }); }
猜你喜欢
相关资源
最近更新 更多
热门标签