Reputation: 12461
I have a drop down implemented as below:
<select (ngModelChange)="onChange($event)">
<option *ngFor="let quantity of quantities" [ngValue]="quantity">
{{ quantity }}
</option>
</select>
The component code is provided:
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, if I change the quantity from the drop-down, the value is not updating. How d I fix it?
Edit:
The code works fine if I use change
in the <selector>
tag:
<select (change)="onChange($event)">
<option *ngFor="let quantity of quantities" [ngValue]="quantity">
{{ quantity }}
</option>
</select>
So, I can work, but, I need to understand why the ngModelChange doesn't work.
Upvotes: 0
Views: 1404
Reputation: 5658
Use (ngModelChange)
with [(ngModel)]
like this:
<select [(ngModel)]="selectedValue" (ngModelChange)="onChange($event)">
<option *ngFor="let quantity of quantities" [ngValue]="quantity">
{{ quantity }}
</option>
</select>
to ensure onChange($event)
is called after [(ngModel)]
updated selectedValue
.
(ngModelChange)
is emitted by [(ngModel)]
after it updated the model.
Upvotes: 0
Reputation: 6016
We should have ngModel
in order to use ngModelChange
where it actually meant to be.
change
is regular change detection of the DOM elements in Angular like input, dropdown and radio inputs.
You can get more idea on this with below
Upvotes: 0
Reputation: 15285
For ngModel
to work, the input need to have a name
attribute. (You should see some errors in the console)
If the drop-down is not bound to a variable for a two-ways binding, there's no value in using ngModel
nor ngModelChange
though.
You should rather use a basic (change)
event:
(change)="onChange($event)
Upvotes: 1