Home > Enterprise >  Angular output with parent and child doesn't work in a button
Angular output with parent and child doesn't work in a button

Time:12-03

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:

I created aand it looks like this

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.

  1. make sure to declare all the component in the same module
  2. make sure you wrote the right event emitter
  3. make sure to import all angular core functions

see working code here: here

  • Related