I'm passing a button event from the child to the parent, but when I click the button, nothing happens.
This is the child code
product-item.component.html
<button (click)='handleShowDetail()' >
product-item.component.ts
@Input()
productItem!: Product;
@Output()
showDetail: EventEmitter<string>=new EventEmitter()
handleShowDetail(){
this.showDetail.emit(this.productItem.sku)
}
This is the code where the product-item is contained
product-list.component.html
<div >
<div
>
<lpr-product-item
(showDetail)="handleShowDetail($event)"
></lpr-product-item>
</div>
</div>
product-list.component.ts
@Output()
showDetail: EventEmitter<string>=new EventEmitter()
handleShowDetail(sku: string){
this.showDetail.emit(sku)
}
This is the parent who should activate the navigate and target the product based on its sku
product-container.component.html
<div >
<div><lpr-products-list
(showDetail)="handleShowDetail($event)"
></lpr-products-list></div>
<div></div>
</div>
product-container.component.ts
handleShowDetail(sku: string){
this.router.navigate([ '/product-details' ])
}
When I click on the button, the user should be redirected to a product detail, but nothing happens
CodePudding user response:
You are not passing the data ($event) from the product-list.component.ts
to product-container.component.html
.
product-list.component.html
<div >
<div
>
<lpr-product-item
(showDetail)="handleShowDetail($event)" // <-- pass parameter
></lpr-product-item>
</div>
</div>
product-list.component.ts
@Output()
showDetail: EventEmitter<string>=new EventEmitter()
handleShowDetail(sku: string){
this.showDetail.emit(sku); // <-- pass parameter
}
Suggestion: As an alternative to passing a variable trough multiple components with event emitters you could use a service.
CodePudding user response:
and the project look like this.
The code works well and emitted from product item component
upto the product container component
even using the same variable as you do.
- make sure to declare all the component in the same module
- make sure you wrote the right event emitter
- make sure to import all angular core functions
see working code here: here