首页 文章

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

提问于
浏览
0

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

在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,但这一次,它返回“undefined”

在parent.html中

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

在child.ts

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

3 回答

  • 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 ));
      }
    
    }
    
  • 0

    ParentComponent 注入 ChildComponent 并按以下方式调用该函数:

    在你的 ChildComponent.ts 中,

    constructor(public parentComponent: ParentComponent) {}
    

    在你的 ChildComponent.html 中,

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

    你将配置定义为 Functionthis.config 只是 formattedVal ,这只是值并且从 parent.ts 定义

    当您想要将值从子节点传递给父节点时,通常会使用 EventEmitter . 不要从父母传给孩子


    所以你可以直接从 parent.ts 获取值

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

    在child.ts

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

相关问题