Having a child component to handle dropdown. Parent component has a reset button to reset the selection made by the user to 'None' in the dropdown (child-component).
Here is the link to the code.
app.component.html:
<app-child [serverData]="serverData" [selectedInpValue]="selectedValue" (selectedComboBoxItemEvent)="getSelectedItem($event)"></app-child>
<!-- reset button -->
<button (click)="resetData()">Reset Selection</button>
2 @Input properties, serverData & selectedInpValue are sent to child component. serverData has the list for the dropdown and selectedInpValue holds the selected value. By default, 'None' is displayed.
server data
this.serverData = [
{
'name': 'None',
'value': 1,
'isSelected': true
},
{
'name': 'Debug',
'value': 2,
'isSelected': false
},
{
'name': 'Error',
'value': 3,
'isSelected': false
}
];
child.component.ts
export class ChildComponent implements OnInit, OnChanges {
selectedItem: any;
@Input() serverData: any[];
@Input() selectedInpValue: any;
@Output() selectedComboBoxItemEvent = new EventEmitter();
ngOnInit() {
this.selectedItem = this.serverData.find(data => data.isSelected);
console.clear();
console.log('child on init: ', this.serverData);
}
ngOnChanges() {
console.clear();
console.log('child old selectedInpValue: ', this.selectedItem);
this.selectedItem = this.selectedInpValue;
console.log('child new selectedInpValue: ', this.selectedItem);
}
selectItem() {
const index = this.serverData.findIndex(x => x.value === this.selectedItem.value);
this.serverData[index].isSelected = true;
for (const data of this.serverData) {
if (data.value === this.selectedItem.value) {
data.isSelected = true;
} else {
data.isSelected = false;
}
}
}
}
child.component.html
<select (change)="selectItem()" [(ngModel)]="selectedItem">
<option *ngFor="let listItem of serverData" [ngValue]="listItem">{{ listItem.name }}</option>
</select>
Issue:
- user selects 'Debug' and clicks on Reset Selection, the selctions resets to None.
- user again selects Debug/Error and clicks on Reset Selection, nothing happens.
First & second click of Reset Selection makes selectedInpValue as-
selectedInpValue = {
'name': 'None',
'value': 1,
'isSelected': true
}
Since, on the second click, the input property selectedInpValue holds the same value as on the first click, the ngOnChanges does not trigger and reset does not happen.
How do I solve this?