Issue
I'm trying to figure out how to cancel mat-select (Angular Material 7.3.7) change event and restore to previous state in event handler. Is it possible?
My select control:
<mat-form-field>
<mat-select #visualOptionsSelect formControlName="competenceVisualOption" (selectionChange)="visualOptionSelectionChanged($event)"
required>
<mat-option *ngFor="let visualOption of availableVisualOptions" [value]="visualOption">
{{visualOption.name}}
</mat-option>
</mat-select>
</mat-form-field>
When some conditions are met I want to cancel selection and leave previous selected item. Using reactive forms I tried to store currently selected item in separate variable and make comparison in valueChanges
subscription of competenceVisualOption
control. But this looks quite messy. Also I have other dependencies on this selected item, therefore I'll need to process them manually too.
I'd really appreciate any help. Thanks in advance
Solution
Well, seems that there is no out-of-the-box feature that I can use. The only way of solving my problem is to store 'last' selected value - I can rollback to it if needed.
My template code:
<mat-form-field>
<mat-select #visualOptionsSelect placeholder="Тип отображения" formControlName="templateCompetenceVisualOption" (selectionChange)="visualOptionSelectionChanged($event.value)"
required>
<mat-option *ngFor="let visualOption of availableVisualOptions" [value]="visualOption">
{{visualOption.name}}
</mat-option>
</mat-select>
</mat-form-field>
In selectionchange event handler - selectionChange
- I always store current selected value and then revert to it after new selection if user answers 'No' to question (I use sweetalert2
library for popups)
visualOptionSelectionChanged(selectedVisualOption: CompetenceVisualOption) {
//если ранее поле было не заполнено, то не задаем вопрос
if (!this.lastActiveVisualOption) {
//перезапишем предыдущее активное значение
this.lastActiveVisualOption = selectedVisualOption;
return;
}
swal({
text: 'При смене отображения вариантов ответов, предыдущие значения сбросятся. Сменить отображение ответов?',
type: 'warning',
showCancelButton: true,
confirmButtonText: 'Да',
cancelButtonText: 'Нет',
confirmButtonClass: "btn btn-primary",
cancelButtonClass: "btn btn-secondary cfb-btn-border",
buttonsStyling: false
}).then((result) => {
if (result.value) {
// перерисуем область ответов
this._setRatingLevelOptionsComponent(selectedVisualOption.code);
//перезапишем предыдущее активное значение
this.lastActiveVisualOption = selectedVisualOption;
}
else {
//если выбрали Нет, то вернем прежний вариант и варианты ответа не трогаем
this.templateCompetenceVisualOption.setValue(this.lastActiveVisualOption);
}
});
}
Answered By - Petr Pokrovskiy
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.