我试图获取多选中最后单击的选项,无论该选项是选中还是未选中。 问题在于选择不是通过模板,而是通过TS动态安装。
我已经尝试在创建选项时添加普通的JS事件监听器,但是不起作用。实际上,我可以获取所有选定的元素,但是我丢失了未选定的选项,因此无法准确获得新的选定元素。
我的HTML
<tr *ngFor="let communityLine of communityLines">
<td>{{communityLine.name}}</td>
<td>{{communityLine.instrument.name}}</td>
<td>{{communityLine.param.name}}</td>
<td>{{communityLine.contextSource.name}}</td>
<td>{{communityLine.sampleType.name}}</td>
<td>{{communityLine.value}}</td>
<td>
<select multiple [id] ="communityLine.apiKey" (change)="eventGetChange(communityLine, $event)" [(ngModel)]="nodeKey">
</select>
</td>
</tr>
我的TS功能
private eventGetChange(commLineKey, event) {
console.log(this.nodeKey);
console.log(commLineKey);
console.log(event.target.value)
我安装选区的TS方法有点复杂,因为我需要显示所有节点(存储在this.allNodes变量中),但要选择其他数组中的节点(nodesInRelation变量)。
private mountSelect(nodesInRelation: Node[], lineApiKey: String): void {
let select = <HTMLSelectElement>document.getElementById(lineApiKey);
let copy = this.allNodes;
for (let node of nodesInRelation) {
copy.forEach((item, index) => {
if (item.name === node.name) copy.splice(index, 1);
});
}
for (let node of nodesInRelation) {
let newoption = new Option(node.name, node.apiKey, null, true);
select.add(newoption);
}
for (let node of copy) {
let newoption = new Option(node.name, node.apiKey, null, false);
select.add(newoption);
}
M.updateTextFields();
M.AutoInit();
}
在eventGetChange函数的第一个console.log中,我获取所有当前选定的值,在第二个中,我获取密钥并且是okey,在第三个中,我仅获取框中的第一个选定元素。
我只希望最后一次单击,选择或取消选择。
谢谢。
答案 0 :(得分:1)
您似乎无缘无故放弃Angular并选择直接进行DOM操作。 Angular完全有能力以编程方式填充选项列表。可能看起来像
<td>
<select multiple [id] ="communityLine.apiKey" [(ngModel)]="nodeKey">
<option *ngFor="let option of optionList; let i = index"
[value]="option" (click)="eventGetChange(option)">{{ option }}
</option>
</select>
</td>
optionList: any[];
private mountSelect(nodesInRelation: Node[], lineApiKey: String): void {
// populate optionList here
}
private eventGetChange(commLineKey) {
// the clicked option is available here
}
答案 1 :(得分:0)
如果您所说的this.nodeKey存储具有所有当前选定值的数组,则只需执行以下操作:
this.nodeKey[this.nodeKey.length - 1]
它将为您提供nodeKey数组中的las值