【问题标题】:Angular 2: emit from child component directly to the parent component's script fileAngular 2:从子组件直接发射到父组件的脚本文件
【发布时间】:2017-06-03 07:50:49
【问题描述】:

我有一个嵌套组件,我希望将一些数据直接发送到父打字稿文件而不​​通过模板。 我不能使用 <child (childEvent)="parentFunc()"></child>

这可能吗?如果是这样,怎么做?

这是事物的当前状态。

parent.component.html(元素必须是这个)

<child #child> </child>

parent.component.ts

@ViewChild('child') public child;

public doSomething() {
  this.child.work();
}

public doThisWhenChildEmits(someData) {
  //?????How do I call this function from child without going through the DOM
  alert(It worked)
}

child.component.ts

@Output() private childEvent: EventEmitter<any> = new EventEmitter()
...
public work() {
   // does some work that changes the child's template
}

public clickToSendBack(){
   // click event that sends back to parent.component directly????
   this.childEvent.emit(someData);
}

【问题讨论】:

    标签: templates angular components parent-child emit


    【解决方案1】:

    如果您不想使用@Output,可以改用Subject

    您的父母会订阅更改。在您的父级中,在组件中声明一个主题,并在构造函数中订阅更改:

    public static changesMade: Subject<any> = new Subject();
    
    //inside constructor the following
    ParentComponent.changesMade.subscribe(res => {
      //call your method here, with the res (someData) you receive from child
      this.doThisWhenChildEmits(res);
    });
    

    在你的孩子身上:

    public clickToSendBack(){
       // send the data to parent
       ParentComponent.changesMade.next(someData)
    }
    

    如果这有帮助,请告诉我! :)

    【讨论】:

    • 谢谢。我认为你的答案会奏效,我想在我承诺前几天给出它并选择你的作为最佳答案。
    • 当然,我明白了! :)
    猜你喜欢
    • 2017-07-09
    • 2018-12-21
    • 2018-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-27
    • 2019-01-06
    相关资源
    最近更新 更多