【问题标题】:Send input with array in angular 5以角度 5 发送带有数组的输入
【发布时间】:2018-07-02 06:31:03
【问题描述】:

在普通的 html 中我们可以这样做:

<input name="xyz[]" value="Lorem" />
<input name="xyz[]" value="ipsum"  />
<input name="xyz[]" value="dolor" />
<input name="xyz[]" value="sit" />
<input name="xyz[]" value="amet" />

结果是发送到服务器的数组。
我怎么能在 Angular 5 中做到这一点?

它的工作方式不一样,也不能在 ngModel 中工作。

【问题讨论】:

  • 仅仅因为你可以,并不意味着你应该;) 你的目标是什么?无限循环,或者你有一个数组长度?
  • 我已经有了长度,并且像这样以角度使用它。 [(ngModel)]="xyz[i]" 但这行不通
  • 我正在给你答复,请稍等

标签: angular forms typescript input angular5


【解决方案1】:

我使用了 angular Form Group,这是解决这个问题的方法:

<div ngModelGroup="xyz">
    <input name="1" ngModel />
    <input name="2" ngModel />
    <input name="3" ngModel />
</div>

【讨论】:

    【解决方案2】:

    由于您的数组有一个长度,您可以使用带有 FormArray 的响应式表单,或者使用模板驱动的表单。既然你说使用后者,你应该这样做:

    <ng-container *ngFor="let item of xyz; let i = index; trackBy: myCustomTrackBy">
      <input type="text" [(ngModel)]="xyz[i]">
    </ng-container>
    

    在你的打字稿中:

    myCustomTrackBy(index, item) { return index; }
    

    【讨论】:

      【解决方案3】:

      我没用过,但你不能用索引吗?

      <input type="text" [(ngModel)]="xyz[0]" />
      <input type="text" [(ngModel)]="xyz[1]" />
      <input type="text" [(ngModel)]="xyz[2]" />
      <input type="text" [(ngModel)]="xyz[3]" />
      

      我在github's issue 看到过这个。

      【讨论】:

        猜你喜欢
        • 2018-09-29
        • 1970-01-01
        • 2016-04-02
        • 1970-01-01
        • 1970-01-01
        • 2020-07-23
        • 2019-04-03
        • 2015-03-25
        • 1970-01-01
        相关资源
        最近更新 更多