如何使用返回值调用父方法 Angular 2?

OPV*_*OPV 1 angular angular5

我在父组件中有两种方法:

public isOpen(index: number): boolean {
    const block = this.dropDownBlocks.find(b => b.index === index);
    return block.open;
  }

  public openDropDown(index: number) {
    const block = this.dropDownBlocks.find(b => b.index === index);
    const i = this.dropDownBlocks.indexOf(block);
    this.dropDownBlocks[i].open = !block.open;
  }
Run Code Online (Sandbox Code Playgroud)

不管做什么。

在我确定的子组件中:

@Output() openTab = new EventEmitter<number>();
@Output() opened = new EventEmitter<number>();
Run Code Online (Sandbox Code Playgroud)

下面在我写的子组件中:

public openDropDown(index: number) {
   this.openTab.emit(index);
}

public isOpen(index: number) {
   return this.opened.emit(index);
}
Run Code Online (Sandbox Code Playgroud)

模板子项是:

<div class="header" (click)="openDropDown(2)"></div>
<div class="body" [hidden]="!isOpen(2)">
Run Code Online (Sandbox Code Playgroud)

这意味着我调用子方法并将主动权转移到具有相同名称的父方法:

public openDropDown(index: number) {
       this.openTab.emit(index);
    }
Run Code Online (Sandbox Code Playgroud)

因此,子组件包含在父组件中,如下所示:

<app-missed-plan (openTab)="openDropDown($event)" (opened)="isOpen($event)"></app-missed-plan>
Run Code Online (Sandbox Code Playgroud)

问题是isOpen()不起作用并且不返回值

小智 7

我在我的实现中使用了回调函数。子组件将值和回调传递给父组件,父组件处理该值并使用回调将该工作的结果返回给子组件。

子组件:

@Output() opened = new EventEmitter<{ value: number, onResult: Function }>()

public isOpen(index) {
    this.opened.emit({
        value: index,
        onResult: (result) => doSomethingWithResult
    })
}
Run Code Online (Sandbox Code Playgroud)

父模板:

<app-parent 
     (opened)="doSomething($event.value, $event.onResult)">
</app-parent>
Run Code Online (Sandbox Code Playgroud)

父组件:

public doSomething(index, onResult) {
    returnValue = doStuffWithIndex
    onResult(returnValue)
}
Run Code Online (Sandbox Code Playgroud)