【问题标题】:How to get selected option using ElementRef?如何使用 ElementRef 获得选定的选项?
【发布时间】:2020-04-22 17:31:58
【问题描述】:

我有一个表格,我可以使用添加按钮将动态行添加到表格中。

为了构建这个表,我采用了数组形式。

每一行都有一个带有选项列表的选择框

场景

一旦用户从选择框中选择了一个选项,并且当他下次单击添加按钮添加新行时,应禁用先前的选择选项。

我能够在代码下方获得选定的选项值表单

  @ViewChild('mySelect') mySelect: ElementRef;

但它总是只给我第一行选择的选项。

【问题讨论】:

  • 没有提到您可能应该考虑以不同的方式进行操作,但是您尝试过@ViewChildren吗?
  • @ViewChildren 也给出了相同的结果,但作为一个列表。

标签: angular viewchild elementref


【解决方案1】:

您不应该使用ElementRef 来实现这一点,因为您将无法控制component.ts 中的数据,您可以简单地按下一个空对象,

<table>

    <tr>
        <th>Gender</th>
    </tr>
    <tr *ngFor="let row of array">
        <td>
            <select [(ngModel)]="row.gender">
        <option value="male">Male</option>
        <option value="female"> Female</option>
      </select>
        </td>
    <td>
      <button (click)="addNewItem()">Add New</button>
    </td>

    </tr>
</table>

打字稿代码

array=[{
    gender:'male'
  }]

addNewItem(){
  const newItem={
     gender:''
  }
  this.array.push(newItem)
}

stackblitz

注意 - 这是一个非常基本的示例,请对此发表评论,以便我可以帮助您构建复杂的示例

【讨论】:

    猜你喜欢
    • 2015-09-01
    • 2012-08-09
    • 1970-01-01
    • 2021-05-15
    • 1970-01-01
    • 2014-05-17
    • 2018-07-24
    • 2016-05-10
    相关资源
    最近更新 更多