如何从子组件触发父组件中的按钮。 Angular 10+

How to trigger a button in Parent component from Child component. Angular 10+

  1. 从子组件向父组件发出值
  2. 在父组件中处理模板中的函数和触发按钮

我的结构 子组件

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

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

因此,一旦子组件从项目列表中选择了客户,我就想在父组件中处理它。 #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>

父组件控制器

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

您可以将 #btnToTrigger 引用传递给 selectCustomer 方法:

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

然后在 selectCustomer 方法中使用相同的方法触发点击:

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