Angular2下拉菜单恢复为先前选择的选项 [英] Angular2 Dropdown revert to previously selected option

查看:114
本文介绍了Angular2下拉菜单恢复为先前选择的选项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have this simple HTML select to implement dropdown in Angular2 (TS) as shown below

<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变量中.更改此设置后,我想打开一个对话框,等待用户响应.如果是用户,请单击取消",然后单击我想将选择还原为以前选择的选项."

The previously selected value is kept in pagination.pageSize variable. And on change of this I wanted to open a dialog box and wait for users response. If user, clicks cancel I want to revert the selection to the previously selected options.

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
  }
}

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

Tried lot of different things but of no luck.

请帮助,我对这件简单的事情失去了信心.我一定在做蠢事.

Please help, I am loosing my mind over this simple thing. I must be doing something stupid.

尝试#1-无效(Plunk- https://embed.plnkr.co/ILi12O/)

Tries #1 - Didn't work (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)使跟踪更加容易.我根据您的调皮器进行了更改:

Try the following. Add ngModelChange method to track the model changes. Keep the change if the dialog confirms and keep the value for the next change, otherwise set back the value. Local template variable (#select) make a little easier to track. I made changes based on your 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;
  } 

朋克车

这篇关于Angular2下拉菜单恢复为先前选择的选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆