如何区分角度组件

问题描述 投票:1回答:2

我有一个带有两个组件子组件的父组件,我想知道哪个子组件生成了一个事件,我的尝试是绑定,但不起作用:

父:

  <span> FIRST CHILD </span>
  <childComponent [childName]=childName1></childComponent>
  <span> SECOND CHILD </span>
  <childComponent [childName]=childName2></childComponent>

  export class ParentComponent implements OnInit {

    childName1: string ="child1";
    childName2: string ="child2";

  }

在孩子:

 <button (click)=event($event)> button </button>


 export class ChildComponent implements OnInit {

       @Input() childName: string;
 }
 ...
 event():void{
      console.log(this.childName);
 }
angular
2个回答
2
投票

你也可以使用

<my-child (event)="onChildEvent($event, 'child1')"></my-child>
<my-child (event)="onChildEvent($event, 'child2')"></my-child>

这样孩子就不需要参与其中。


1
投票

解决你的问题,看看

StackBlitz: Demo

Child会触发事件,并让父母知道哪个孩子解雇了它

  1. 此方法甚至适用于动态生成的子组件
  2. 孩子也可以立即发送额外的数据和身份证明。
© www.soinside.com 2019 - 2024. All rights reserved.