如何将函数从父级传递给深层嵌套的子级并将@input 值用于Angular 8中传递的函数?

Posted

技术标签:

【中文标题】如何将函数从父级传递给深层嵌套的子级并将@input 值用于Angular 8中传递的函数?【英文标题】:How to pass a function from a parent to a deep nested child and use an @input value into the passed function in Angular 8? 【发布时间】:2020-08-23 13:11:43 【问题描述】:

在这种情况下我有 3 个组件:

-OuterComponent
--MiddleComponent
---InnerComponent

我需要通过 MiddleComponent 将一个函数从 OuterComponent 传递给 InnerComponent。

值得一提的是,我需要传递的函数确实需要输入:DoSomething(node)

我不知道它是否相关,但我已经将 NodeTree 从 OuterComponent 传递到 MiddleComponent,然后我将 NodeTree 解包到 Node 中并将其传递给 InnerComponent。这个节点是我需要用作传递函数的输入的。

所以,我需要能够使用@Input 作为传递给 InnerCompoenent 的函数的输入,我假设它需要是一个@output。

【问题讨论】:

你想通过输入和输出装饰器将值从外部组件传递到内部组件吗?或者你可以使用服务通过 @RenceAbishek 如果可能的话,我想通过输入和输出装饰器来完成它,因为我想调用的函数确实调用了类中的其他函数,如果我必须将一半的逻辑移出想要使用服务。 【参考方案1】:

方法一: 您可以使用@Output 从子组件(InnerComponent)调用父组件函数(OuterComponent)。

外部组件 html

<MiddleComponent (updateOuterComponent)="parentFunction($event)" />

外部组件 TS:

export class OuterComponent implements OnInit 

    constructor() 

    ngOnInit() 

    parentFunction(para) 
      console.log(para);
      // operations you want to do in parent component
    


中间件 HTML:

<InnerComponent (updateMiddleComponent)="middleFunction($event)" />

中间组件 TS:

export class MiddleComponent implements OnInit 

   @Output() updateOuterComponent = new EventEmitter();

    constructor() 

    ngOnInit() 

    middleFunction(para) 
      this.updateOuterComponent.emit(para);
    


内部组件 HTML: 想写什么就写什么

内部组件 TS:

export class InnerComponent implements OnInit 

       @Output() updateMiddleComponent = new EventEmitter();

        constructor() 

        ngOnInit() 

        updateMiddleAndParent(para) 
          this.updateMiddleComponent.emit(para);
        

    

一旦您使用发射器从内部组件调用updateMiddleAndParent 函数,就会触发MiddleComponent 中的middleFunction。触发middleFunction后,同样middleFunction会在emitter的帮助下触发parentFunction。

方法二: 您需要创建一个服务并使用它来调用父函数:

数据服务:

import BehaviorSubject from "rxjs/BehaviorSubject"

export class DataService 
    private state$ = new BehaviorSubject<any>('initialState');

    changeState(myChange) 
        this.state$.next(myChange);
    

    getState() 
        return this.state$.asObservable();
    

在 InnerComponent 和 OuterComponent 中调用 DataService: 在 OuterComponent 调用 DataService 并调用 getState() 时,这将返回一个 observable,只要值发生变化,您就可以使用在 observable 响应中传递的数据进行任何函数。

在 InnerComponent 调用 DataService 并使用changeState() 更改值。

一旦在 DataService 中更改了值,那么在父组件中,值将随着您订阅 observable 而更改,您将从那里获取更新的数据,您可以调用父组件中的任何函数。

【讨论】:

以上是关于如何将函数从父级传递给深层嵌套的子级并将@input 值用于Angular 8中传递的函数?的主要内容,如果未能解决你的问题,请参考以下文章

React useContext 不会将值传递给深层嵌套的子级

在 React 中将数据从父级传递给子级

如何通过事件将数据从父级传递给子级

Vue 组件:如何将数据从父级传递给子级

使用 XLPagerTabStrip 将数据从父级传递给子级

将动态插槽从父级传递到子级到孙子级