【问题标题】:Angular2+ how to let child get notification from parentAngular 2如何让孩子从父母那里得到通知
【发布时间】:2017-09-03 17:12:47
【问题描述】:

对于Angular2+,我们可以使用@output来通知父级,有没有办法让子级知道在Child事件发出之前或之后调用了哪个父函数?

下面是父 HTML 代码,会调用子组件执行 onClick 或 OnClose 函数。

<child-comp (test1)="onClick()">
    ...
</child-comp>

<child-comp (test2)="onClose()">
    ...
</child-comp>

下面是子代码。

@Component({
    selector: 'child-comp'
})

export class ChildComponent{
    @Output() test1: EventEmitter<any> = new EventEmitter();
    @Output() test2: EventEmitter<any> = new EventEmitter();

    handleClick() {
        //this.test1.emit("test1 is emitted");
        //or 
        //this.test2.emit("test2 is emitted");

    }
}

问题是test1和test2都在handleClick函数中,一旦test1或test2事件发出,如何让child知道执行了哪个父函数?

【问题讨论】:

  • 您想知道父母订阅的是test1 还是test2?你真正试图解决的问题是什么?您可以同时发出两者,由父级决定使用哪一个。
  • 我猜你对事件发射器感到困惑检查这个link

标签: angular


【解决方案1】:

为孩子添加一个@Input() 属性whatHappendInParent 并编写如下内容:

<child-comp (test1)="onClick()" [whatHappenedInParent] = whatHappened>
    ...
</child-comp>

<child-comp (test2)="onClose()" [whatHappenedInParent] = whatHappened>
    ...
</child-comp>
...
export class myParent {
  whatHappened: string;
  onClick(){
   this.whatHappened = "onClick was called";
  }
  onClose(){
   this.whatHappened = "onClose was called";
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-08-10
    • 1970-01-01
    • 1970-01-01
    • 2017-05-31
    • 2017-07-01
    • 1970-01-01
    • 2018-09-22
    • 1970-01-01
    相关资源
    最近更新 更多