I have this angular code, which is a function called in emit of output.
addToCart(product: Product) {
alert(product.name);
}
And on my child component:
export class ProductListComponent implements OnInit {
@Input() products: Product;
@Output() onAddToCart: EventEmitter<Product> = new EventEmitter();
@Output() onQuantityUpdate: EventEmitter<Product> = new EventEmitter();
prod: Product[] = PRODUCTS;
cart?: Cart;
id?:number = 1;
ngOnInit() {}
isAddVisible = this.prod.map(() => false);
isAddCartVisible = this.prod.map(() => true);
cartQuantity = this.prod.map(() => 1);
togglePropVisible(i: number): void {
this.isAddVisible[i] = !this.isAddVisible[i];
this.isAddCartVisible[i] = !this.isAddCartVisible[i];
this.products[i].cartQuantity = 1;
this.onAddToCart.emit(this.products);
}
My question now is why product.name in addToCart is showing an “undefined” value. Can anyone help me with this?
3
You have typed the products
input incorrectly, and are using it sometimes like an array and sometimes like an object. I wonder how TypeScript allowed this. In your onAddToCart
event emitter you are expecting a Product
object instead of an array. Updated code:
export class ProductListComponent {
@Input() products: Product[];
@Output() onAddToCart: EventEmitter<Product> = new EventEmitter();
togglePropVisible(i: number): void {
this.products[i].cartQuantity = 1;
this.onAddToCart.emit(this.products[i]);
}
}
3