【问题标题】:Angular 2: Programmatically selecting option in combobox in all the rows in tableAngular 2:以编程方式在表中所有行的组合框中选择选项
【发布时间】:2016-12-15 12:25:17
【问题描述】:

我正在使用带有 TypeScript 的 Angular 2 构建应用程序。我有下表,其中一列中包含选择控件。选择控件内容绑定到另一个字符串数组 -

    <table ngControl="lstClasses" name="lstClasses">
        <tr *ngFor="let class of model.Classes">
            <td>{{class.Name}}</td>
            <td>
                <select name="cmbSection" [(ngModel)]="class.Section">
                    <option *ngFor="let section of sections"
                        [ngValue]="section">
                        {{section}}
                    </option>
                </select>
            </td>
        </tr>
    </table>

其中 Class 是 {Name: string, Section: string} 类型的对象 section 是一个字符串[] = ["White", "Blue", "Purple", "Green", "Red"]。

当我在任何行的任何组合框中更改所选选项时,它会正确反映在模型中。当我保存并刷新数据时,所有行中的所有选择控件都显示与表中最后一行一起保存的选定选项。

例如,如果我在表格的最后一行选择“紫色”并保存它,当数据刷新时,所有行都会显示“紫色”作为选定选项,即使模型包含正确的选项。

你能帮我解决一下我哪里出错了吗?

【问题讨论】:

    标签: html angular typescript combobox


    【解决方案1】:

    我认为你看起来像下面这样,

     <option *ngFor="let section of sections"
                        [value]="section"
                        [selected]="section == class.Section"
                        >
                        {{section}}
     </option>
    

    这里是Plunker!!

    【讨论】:

    • 感谢 Madhu 的回复,但此解决方案不起作用。问题是当我在 List 或 Table 控件中使用组合控件时,它可以正常工作。
    • @Raj:为相同添加了Plunker,这是相同的场景吗?
    • 是的,情况相同。当我在 Select 语句中使用 [(ngModel)]="class.Section" 时,看起来我遇到了问题。没有这个,我可以从底层对象正确读取值,但它不会反映目标对象上的更新选项。
    • 这是完美的。感谢马杜的解决方案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多