Angular 2,从循环外的按钮访问选择值

时间:2018-10-26 15:48:10

标签: angular

注意此代码:(click)=“ deleteDescriptor(descriptor.DescriptorId,#fc + i)

所有选择都是动态构建的。因此,当他们单击特定选择旁边的删除按钮时,我尝试访问选择的值。有道理吗?

<ng-container *ngFor="let descriptor of descriptors; let i = index">

                    <label for="descriptor_{{descriptor.DescriptorId}}">{{descriptor.Display}}</label>
                    <span *ngIf="descriptor.IsEditable">
                        <button type="button" class="smAddBtn" (click)="openModal(descriptor.DescriptorId, descriptor.Name)">Add</button>
                        | <button type="button" class="smAddBtn" (click)="deleteDescriptor(descriptor.DescriptorId, #fc+i)">Delete</button>
                    </span>
                    <ng-container *ngIf="descriptor.IsMultiple == true">
                        <select multiple class="form-control" id="descriptor_{{descriptor.DescriptorId}}" [formControlName]="descriptor.Name" #fc+i>
                            <option value=""></option>
                            <option *ngFor="let item of descriptor.Items" [value]="item.DescriptorId">{{item.Name}}</option>
                        </select>
                    </ng-container>
</ng-container>

2 个答案:

答案 0 :(得分:0)

不确定最后是否要删除Select中的选定值,但这是我为您准备的:

首先,您必须更改Select的ID,以确保其在页面中是唯一的。因为现在您可能会与LabelSelect发生冲突。

<select multiple class="form-control" id="selector_descriptor_{{descriptor.DescriptorId}}"[formControlName]="descriptor.Name" #fc+i>

在TypeScript组件中,我得到了:

deleteDescriptor(id, dunno) {
    let select: HTMLSelectElement = <HTMLSelectElement>document.getElementById(`select_descriptor_${id}`);
    select.remove(select.selectedIndex);
}

答案 1 :(得分:0)

您可以访问formControl的值,而不是模板引用。

<button type="button" class="smAddBtn" (click)="deleteDescriptor(descriptor.DescriptorId, yourForm.get(descriptor.Name).value)">Delete</button>