I have successfully implemented a dropdown feature like this:
<select (ngModelChange)="onChange($event)">
<option *ngFor="let quantity of quantities" [ngValue]="quantity">
{{ quantity }}
</option>
</select>
The component code is presented below:
export class ProductItemComponent implements OnInit {
@Input()
productItem: Product;
@Output()
addProduct: EventEmitter<Product> = new EventEmitter();
@Output()
selectedQuantity: EventEmitter<Number> = new EventEmitter();
quantities: number[] = [];
constructor(private productService: ProductsService) {
this.productItem = {
id: 1,
name: '',
price: 0.0,
url: '',
description: ''
};
this.quantities = Array.from({ length: 30 }, (_, i) => i + 1);
}
ngOnInit(): void {}
addToCart(p: Product): void {
this.addProduct.emit(p);
}
public onChange(event: any): void {
const quantity = event.target.value;
console.log('\n');
console.log('quantity ' + quantity);
console.log('\n');
this.selectedQuantity.emit(quantity);
}
showProductDetails(product: Product): void {
this.productService.setCurrentProduct(product);
}
}
However, there is an issue where the quantity value is not updating when changed in the dropdown. How can I address this problem?
Edit:
I have found that changing ngModelChange
to change
in the <selector>
tag resolves the issue:
<select (change)="onChange($event)">
<option *ngFor="let quantity of quantities" [ngValue]="quantity">
{{ quantity }}
</option>
</select>
While this workaround works, I am curious as to why ngModelChange
does not function as expected.