gpt4 book ai didi

javascript - Angular2 Dropdown 恢复到以前选择的选项

转载 作者:太空狗 更新时间:2023-10-29 18:24:55 25 4
gpt4 key购买 nike

我有这个简单的 HTML 选择来实现 Angular2 (TS) 中的下拉菜单,如下所示

<select id="pageSize" (change)="onPageSizeChanged($event, pagination.pageSize)">
<option value="10">10</option>
<option value="20">20</option>
<option value="50">50</option>
</select>

先前选择的值保存在 pagination.pageSize 变量中。在更改此设置时,我想打开一个对话框并等待用户响应。如果用户单击取消,我想将选择恢复为之前选择的选项。

onPageSizeChanged(event, oldValue) {
const response = window.confirm("Are you sure you want change the page size? Your edits will be lost?");
if (response) {
//... some code ...
} else {
//... here I want to revert the selection to previously selected option
}
}

尝试了很多不同的东西,但没有运气。

请帮忙,我对这个简单的事情失去了理智。我一定是在做傻事。


尝试 #1 - 没有成功(Plunk - https://embed.plnkr.co/ILi12O/)

<select id="pageSize" [ngModel]="pageSize" (ngModelChange)="onPageSizeChanged($event, pagination.pageSize)"> 
<option value="10">10</option>
<option value="20">20</option>
<option value="50">50</option>
</select>

onPageSizeChanged(event, oldValue) {
const response = window.confirm("Are you sure you want change the page size? Your edits will be lost?");
if (response) { //go ahead so something }
else { this.pageSize = oldValue; }
}

最佳答案

添加 ngModelChange 以跟踪模型更改。如果对话框确认下一次更改,则保留更改,否则设置回该值。本地模板变量 (#select) 更容易跟踪。我根据您的 plunker 进行了更改:

HTML:

 <select #select id="pageSize" [ngModel]="pageSize" (ngModelChange)="select.value = onPageSizeChanged($event)"> 

typescript :

   onPageSizeChanged(event) { 
const response = window.confirm("Are you sure you want change the page size? Your edits will be lost?");
console.log(this.pagination.pageSize)
if (response) {
this.pageSize = event;
this.pagination.pageSize = event;
}
else{
this.pageSize = this.pagination.pageSize;
}
return this.pagination.pageSize;
}

demo

关于javascript - Angular2 Dropdown 恢复到以前选择的选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46357952/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com