Home > Net >  How to trigger a button in Parent component from Child component. Angular 10
How to trigger a button in Parent component from Child component. Angular 10

Time:02-19

  1. Emit value from child component to the parent
  2. In the parent component handle the function and trigger button in the template

My Structure Child component

export class ChildComponent {
 @Output() selectCustomer = new EventEmitter<Customer>();

 onSelectCustomer(customer: Customer) {
        this.selectCustomer.emit(customer);
 }
}

So once the child component selects the Customer from the List of Items I want to handle it in parent component. #btnToTrigger

<parent-component>
...
   <child-component
     (selectCustomer)=selectCustomer($event)>  <-- emits value
   </child-component>
...
   <button #btnToTrigger>Continue</button> <--How to trigger this button after child component emits value in controller?
</parent-component>

Parent Component Controller

export class ParentComponent {
     ...
    
     selectCustomer(customer: Customer) {
           console.log(customer);
           //Value Emited, but how to trigger button in same component template from here?
           //#btnToTrigger
     }
    }

CodePudding user response:

You can pass the #btnToTrigger reference to selectCustomer method as:

<child-component
    (selectCustomer)=selectCustomer($event, btnToTrigger)>
</child-component>
<button #btnToTrigger (click)="onClick()">Continue</button>

and then use the same within your selectCustomer method to trigger the click:

selectCustomer(customer: Customer, buttonElement: HTMLButtonElement) {
  console.log(customer);
  buttonElement.click();
}
  • Related