我有一个下拉菜单,根据下拉选择,我在文本框中获取值。但是,如果我要更新任何文本框,然后单击下拉列表并更改值而未单击保存按钮,则它不应允许更改值。
constructor(private _route: ActivatedRoute, private _router: Router, private spinnerService: Ng4LoadingSpinnerService, private _http: AsyncHttpService, private _logger: AppLoggerService,
private confirmationDialogService: ConfirmationDialogService, private _alertService: AlertService, private _messageService: MessageService) { }
@HostListener('window:beforeunload', ['$event'])
browserCanActivate($event) {
if (this.isDataChanged == true) {
$event.returnValue =
this._messageService.warningChangesNotSaved;
return;
}
}
canDeactivate(): Observable<boolean> | boolean {
return !(this.isDataChanged == true);
}
//Host Listner for Up and Down Arrow (KeyboardEvent)
@HostListener('document:keydown', ['$event'])
handleKeyboardEvent(event: KeyboardEvent) {
this.showDropdownEle(event);
}
onCurrentSnapshotPeriodChange = ($event: any) => {
if (this.isDataChanged == true) {
debugger
var z = event.returnValue;
// $event.returnValue =
// this.confirmationDialogService
// return
}else{
this.periodName = $event.periodName;
this.hasValuation = true;
//refresh the page with new period
this.getDealFinancialMetrics();
}
因此,我在这里检查数据是否已更改,但是我无法恢复到先前的选择,例如,下拉菜单中是否有A,B,C,D作为选项,默认情况下,我看到已选择A如果我在文本框中进行了任何更改,然后当我尝试从下拉菜单中单击B时,除非我不单击“保存”按钮,否则应该无法进入B并出现一个弹出窗口,提示您是否要保存更改确定并取消按钮。如果我单击“取消”,那么我应该仍然在下拉菜单A中;如果我单击“确定”按钮,那么我应该在下拉菜单b中。
请参见此StackBlitz链接StackBlitz
您可以使用@ViewChild来获取下拉列表和文本框的更改值。那么您需要一个对象作为参考。对象结构是这样的。.
textChangeValue ={
changed : false,
dropdownValue: '',
previousTextValue:'',
currentTextValue:'',
saveValue:{
saveDropdownValue: '',
saveTextValue:''
}
};
您的onChange下拉列表看起来像这样...
onChange(value){
if ((this.selectDropdown.nativeElement.value !== this.selectText.nativeElement.value) && (this.textChangeValue.changed !== false) ){
let confirmValue = confirm('Do you want to save change');
if (confirmValue){
this.save();
this.textChangeValue.dropdownValue= this.selectDropdown.nativeElement.value;
this.selectText.nativeElement.value =
this.selectDropdown.nativeElement.value;
}
else{
this.selectDropdown.nativeElement.value = this.textChangeValue.dropdownValue;
this.selectText.nativeElement.value = this.textChangeValue.currentTextValue;
}
}else{
this.selectText.nativeElement.value = value
this.textChangeValue.currentTextValue = value;
this.textChangeValue.dropdownValue = value;
}
}
您的html模板看起来像这样...
<select #selectDropdown (change)="onChange($event.target.value)">
<option value=''>Select</option>
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
</select>
<input #selectText type="text" (change)="onTextChange($event)">