调用父方法并从子方法获取返回值

时间:2018-12-10 06:22:55

标签: angular

我的目标是,从子组件开始,我想在父组件中调用一个方法并获取返回值。我尝试了以下方法,但没有成功。

在parent.html

<child-component [config]="getConfig(data)"></child-component>

在parent.ts中

data = <some data>
...
getConfig(val) {
    // format value and return
    return formattedVal;
}

在child.ts中

@Input() config: Function
...
retrieve() {
    const conf = this.config();
}

我收到错误消息“ this.config不是函数”

此外,我尝试使用EventEmitter,但这一次,它返回了“未定义”

在parent.html

<child-component (config)="getConfig(data)"></child-component>

在child.ts中

@Output() config = new EventEmitter();
...
retrieve() {
    const conf = this.config.emit;
}

3 个答案:

答案 0 :(得分:0)

您将config定义为Function,但是this.config只是formattedVal,它只是值,是根据parent.ts定义的。

EventEmitter通常用于要将值从子级传递到父级的情况。不要从父母传给孩子


因此您可以直接从parent.ts获取值

在这种情况下,如上所述,该值为formattedVal

在child.ts

@Input() config
...
retrieve() {
    const conf = this.config;
}

答案 1 :(得分:0)

基本上,您想要做的是将一个函数传递给孩子并对其执行任何操作。因此,例如在父组件中,您有一个“ returnRandom”函数,该函数返回一个随机数,上限为用户对该函数传递的值,但是可悲的是,您可能需要将数据放入全局范围。

  

父组件TS

import { Component } from '@angular/core';

const parentGlobalVar = 10;

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {

  parentLocalVar = 0;


  public returnRandom(max: number): number {
    console.log(parentGlobalVar); // logs '10'
    console.log(this.parentLocalVar); // logs 'undefined'
    return Math.floor(
      Math.random() * max + 1
    );
  }

}

然后将函数传递给html标签处的子组件

<app-child [parentFn]="returnRandom"></app-child>

然后将函数调用到Child组件,并从中进行所需的操作。

import { Component, OnInit, Input } from '@angular/core';

@Component({
  selector: 'app-child',
  templateUrl: './child.component.html',
  styleUrls: ['./child.component.scss']
})
export class ChildComponent implements OnInit {

  @Input() parentFn: Function;

  constructor() { }

  ngOnInit() {
    console.log(this.parentFn( 100 ));
  }

}

答案 2 :(得分:0)

ParentComponent注入ChildComponent并按如下所示调用函数:

在您的ChildComponent.ts中,

constructor(public parentComponent: ParentComponent) {}

在您的ChildComponent.html中,

<child-component [config]="parentComponent.getConfig(data)"></child-component>