I need some help in getting the unit price by selecting the ingredient name in the dropdown. So what i did is i get the index from the formArray. I also got the ingredient id and minus it by 1 and put in the index of the ingredients just to match the index from the formArray. But is there some other way? because if there are some changes in my database in the future like when i delete an ingredient from the database, then the id will be skip on. Please see my codes below.
Here's also my stackblitz link. CLICK THIS LINK FOR STACKBLITZ
onSelectIngredient(event,i): void {
this.patchValues(event.target.value,i);
}
patchValues(id,i) {
let x = (<FormArray>this.addForm.controls['rows']).at(i);
console.log(x);
x.patchValue({
unit_price: this.ingredients[id - 1].price
});
}
You can find ingredient by id like below selectedIngredient
.
patchValues(id,i) {
let x = (<FormArray>this.addForm.controls['rows']).at(i);
const selectedIngredient = this.ingredients.find(y => y.id == id); // beware of number and string
x.patchValue({
unit_price: selectedIngredient.price
});
}