【问题标题】:Bind selected dropdown option to variable将选定的下拉选项绑定到变量
【发布时间】:2016-11-24 00:34:07
【问题描述】:

我有一个看起来像这样的ngFor 循环(经过简化以便更容易理解):

<div *ngFor="let c of customers">
    <button class="save green-button" type="button" (click)="editCustomer(c.CustomerId, method.value)">Save</button>

    <select *ngIf="c.GrowMethodsAvailable.length" id="PerProjectGrowMethodId" name="PerProjectGrowMethodId" #method>
        <option *ngFor="let method of c.GrowMethodsAvailable" [ngValue]="method.Value">{{method.Text}}</option>
    </select>   
</div>

如您所见,有一个保存按钮和一个带有动态选项的选择下拉菜单。当我单击保存按钮时,我需要它发送我从相应下拉列表中选择的任何值。我知道如何将值绑定到我在我的类中创建的变量,但可能有 10 个不同的保存按钮,其中选择了 10 个不同的值,所以我假设我需要为每个选择下拉菜单设置一个局部变量。我在选择元素中添加了#method,并在保存按钮的(click)="editCustomer(c.CustomerId, method.value)" 函数中添加了method.value。当我尝试这样做时,出现以下错误:

无法读取未定义的属性“值”

如何将所选选项中的值绑定到相应的保存按钮中,以便为每个选项发送正确的值?

【问题讨论】:

    标签: angular ngfor


    【解决方案1】:

    您的绑定的问题是,在 *ngFor 内部为客户重复 #method 会破坏模板引擎对选择的句柄。为了改变它并让它工作,我们需要改变我们的方法并抛弃模板变量,因为它们是静态定义的:

    为了我们的利益,我们可以在这里滥用 JS,在你的组件中添加一个将跟踪所选项目的属性:

    component.ts

    selected = [];
    

    在 HTML 模板中,我们将在按钮和选择中访问该属性:

    <div *ngFor="let c of customers">
            <button class="save green-button" type="button" (click)="editCustomer(c.CustomerId, selected[c.CustomerId])">Save</button>
    
            <select *ngIf="c.GrowMethodsAvailable.length" [(ngModel)]="selected[c.CustomerId]">
                <option *ngFor="let method of c.GrowMethodsAvailable" [ngValue]="method.Value">{{method.Text}}</option>
            </select>
        </div>
    

    Plunker:http://plnkr.co/edit/bWnlJfydPbUxeeI6a715?p=preview

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-23
    • 2012-06-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多