I have an Angular dropdown component (CustomDropdownComponent) that receives a list of options and a selected value from its parent component via @Input(). The parent also listens for selection changes using @Output().
However, I intentionally did not update the selectedValue in the parent when handling the (selectionChange) event to see if the dropdown would revert to the default selection. Surprisingly, the dropdown still updates to the newly selected option, even though the parent state remains unchanged.
My Questions:
- Why does the dropdown update the selected option even though the parent does not store the new value?
- Is this behavior due to Angular's change detection or how property bindings work?
- How can I ensure that the dropdown only displays what the parent provides and does not retain a selection unless explicitly stored in the parent?
Here is a simplified version of my implementation:
Parent Component (app.component.ts)
export class AppComponent { options = [ { value: '1', text: 'Option 1' }, { value: '2', text: 'Option 2' }, { value: '3', text: 'Option 3' } ]; selectedValue = ''; // Intentionally not updating this when selection changes handleOnChange(event: any) { console.log(event.target.value); // Logging the value but not saving it } } Parent Component Template (app.component.html)
<app-custom-dropdown [options]="options" [selected]="selectedValue" (selectionChange)="handleOnChange($event)"> </app-custom-dropdown> Child Component (custom-dropdown.component.ts)
@Component({ selector: 'app-custom-dropdown', templateUrl: './custom-dropdown.component.html', styleUrls: ['./custom-dropdown.component.scss'] }) export class CustomDropdownComponent { @Input() options: { value: string; text: string }[] = []; @Input() selected: string = ''; @Output() selectionChange: EventEmitter<any> = new EventEmitter<any>(); onChange(event: any) { this.selectionChange.emit(event); // Emitting value but parent does not save it } } Child Component Template (custom-dropdown.component.html)
<select (change)="onChange($event)" [value]="selected"> <option value="" hidden>default</option> <option *ngFor="let option of options" [value]="option.value"> {{ option.text }} </option> </select>