【问题标题】:ngModel is not working when an input field is repeated with the property inside the repeated array's object is used in [(ngModel)]当在 [(ngModel)] 中使用重复数组对象内的属性重复输入字段时,ngModel 不起作用
【发布时间】:2018-04-05 11:40:33
【问题描述】:

我实际上是在重复一个 mat 输入字段,然后我将数组中对象的属性名称写入 [(ngModel)] 作为 [(ngModel)] 的值

例如,这是我拥有的对象数组:

test = [{name: 'Harish'},{name: 'Pushpa'}]

所以在 html 中我重复了这个数组,如下所示:

 <mat-form-field class="example-full-width" *ngFor="let i of test"> 
<input  matInput placeholder="Favorite food" [(ngModel)]='i.name' name='trtrtrtrt'>


</mat-form-field>

但是它将所有输入字段的值显示为数组中最后一个元素的名称

这是我遇到的问题的工作plunker

【问题讨论】:

    标签: angular angular-material2


    【解决方案1】:

    我遇到了非常相似的问题(在角度 7 中) - 无法在堆栈中追踪为什么在其他组件中完全相同的代码工作时会发生这种情况。我对双向绑定的解决方法是:

      <mat-form-field class="example-full-width" *ngFor="let i of test"> 
        <input matInput placeholder="Favorite food" [value]="i.name"  (input)="i.name = $event.target.value" [name]='i.name'>   
      </mat-form-field>
    

    即使用 [value] 和 (input) 绑定。

    【讨论】:

    • 这太棒了。谢谢。效果很好。
    【解决方案2】:

    不同的input 应该有不同的name 属性。

    <mat-form-field class="example-full-width" *ngFor="let i of test"> 
        <input  matInput placeholder="Favorite food" [(ngModel)]='i.name' [name]='i.name'>
    </mat-form-field>
    

    你可以在plunker找到结果

    【讨论】:

    • 谢谢你,我会尽力让你知道
    【解决方案3】:

    试试这个

     <mat-form-field class="example-full-width" *ngFor="let i of test"> 
    <input  matInput placeholder="Favorite food" value="{{i.name}}" name='trtrtrtrt'>   
    </mat-form-field>
    

    【讨论】:

    • 值工作正常,但我想在这里使用两种方式的数据绑定
    • @you can't do it in using loop
    • 我该怎么做?你能编辑我在问题中发布的 plunker 并给我看吗?
    • @pushplatapatel 让我弄清楚。
    • 好的,等待您的答复
    猜你喜欢
    • 1970-01-01
    • 2015-03-25
    • 2018-04-12
    • 1970-01-01
    • 1970-01-01
    • 2017-08-03
    • 2019-08-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多