Is there a way to reset an Angular Material Select Component to its default value after manually changing it on the UI screen? It seems to work fine during initialization but not after manual changes.
I am attempting to create a button that will revert the Select Component back to its default value. I have looked into using NgOnChanges, but I am already utilizing get setters.
HTML:
<div class="dropdown-cont">
<mat-form-field appearance="outline">
<mat-label>{{label}}</mat-label>
<mat-select
disableOptionCentering
[disabled]="disabled"
[ngStyle]="styles"
[(ngModel)]="selectedItem"
(selectionChange)="selectedItemChanged($event)"
>
<mat-option [value]="defaultItem[txtValue]">{{defaultItem[txtField]}}</mat-option>
<mat-option
*ngFor="let item of listItems"
[value]="item[txtValue]"
>
{{item[txtField]}}
</mat-option>
</mat-select>
<mat-hint>{{hint}}</mat-hint>
</mat-form-field>
</div>
Typescript:
import { Component, OnInit, Input, EventEmitter, Output, forwardRef } from '@angular/core';
import { DropdownItem, DropdownComponent } from '../dropdown/dropdown.component';
import { NG_VALUE_ACCESSOR } from '@angular/forms';
@Component({
selector: 'app-drop-down',
templateUrl: './drop-down.component.html',
styleUrls: ['./drop-down.component.scss'],
providers: [
{
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => DropdownComponent),
multi: true
}
]
})
export class DropDownComponent implements OnInit {
ngOnInit() {
}
//#region Members
private _listItems = [];
onChange: any = () => { };
onTouch: any = () => { };
//#endregion
//#region Inputs
@Input()
set listItems(data: Array<DropdownItem>) {
this._listItems = data;
this.selectedItem = undefined;
}
get listItems() {
return this._listItems;
}
@Input() label = '';
@Input() styles: any = {};
@Input() txtField: any;
@Input() txtValue: any;
@Input() disabled: boolean;
@Input() defaultItem: object;
@Input() selectedItem: DropdownItem;
@Input() primitive = false;
@Input() hint = '';
//#endregion
//#region Outputs
@Output() selectedItemOutput = new EventEmitter();
//#endregion
//#region ControlValueAccessor
set value(val) {
this.selectedItem = val;
this.onChange(val);
this.onTouch(val);
}
writeValue(obj: any): void {
this.selectedItem = obj;
this.value = obj;
}
registerOnChange(fn: any): void {
this.onChange = fn;
}
registerOnTouched(fn: any): void {
this.onTouch = fn;
}
setDisabledState?(isDisabled: boolean): void {
this.disabled = isDisabled;
}
//#endregion
//#region Event Handlers
selectedItemChanged(selectItem) {
this.onChange();
let outputData: any;
if (selectItem.value == this.defaultItem[this.txtValue]) {
outputData = this.defaultItem;
} else {
outputData = this.listItems.find(x => x[this.txtValue] == selectItem.value);
}
this.selectedItemOutput.emit(outputData);
}
//#endregion
}