【问题标题】:How to set the name tag in a ngFor* loop dynamically?如何在 ngFor* 循环中动态设置名称标签?
【发布时间】:2019-02-01 14:12:02
【问题描述】:

我正在尝试使用来自ngFor 循环的值动态设置名称标签。给id标签赋值是没问题的,但是对于name标签就不行了。

<table class="compactTable">
  <tr *ngFor="let s of ps.State; let i = index;" >
    <td class="alignRight" width="15%">
        <input type="text" id ="{{i}}" (change)="check($event)" name ="{{i}}" [(ngModel)]="s.ZBez"> 
    </td>
  </tr>
</table>

我将onChange 传递给check() 函数的$eventid 等于i,但name 始终是一个空字符串。为什么它们不同?如何动态设置name

【问题讨论】:

  • 我认为您的代码没有任何问题。它应该工作正常。你能提供一个演示吗?

标签: html angular typescript dynamic ngfor


【解决方案1】:

您需要像[attr.ATTR_NAME] 一样使用它,并且没有双括号。

<input type="text" [attr.id]="i" (change)="check($event)" [attr.name]="i" [(ngModel)]="s.ZBez"> 

您可以查看有关模板语法的官方文档以获取更多信息:

https://angular.io/guide/template-syntax

更新

正如@ConnorsFan 在评论中所说,属性绑定也应该起作用。我创建了一个具有所有可能性的 stackblitz 项目。请查看:

https://stackblitz.com/edit/angular-ckp8fz

【讨论】:

  • 他为什么“需要”使用属性绑定?属性绑定也应该有效,不是吗?
  • 其实你是对的。 “需要”不是正确的词。我编辑了答案
【解决方案2】:

你可以试试[name]="i"

<input type="text" id ="{{i}}" (change)="check($event)" [name]="i" [(ngModel)]="s.ZBez"> 

编辑:对于 id,您可以尝试相同的 [attr.id]="i"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-12-16
    • 2016-04-06
    • 2020-02-20
    • 1970-01-01
    • 2014-09-07
    • 1970-01-01
    • 2012-01-05
    相关资源
    最近更新 更多