首页 > 解决方案 > Angular2+ - 如何动态选择子组件并调用它的函数?

问题描述

我有一个关于 Angular2 +(不是 AngularJs)的问题。我是一名 Vue.js 程序员,我很好奇在 Angular 中是否可行。

想象一下,您有一个包含许多执行许多任务的模块的应用程序。您有一个负责监控模块状态的前端应用程序;显示日志、错误、通知用户某些模块已完成工作等。这些模块通过 WebSocket(或 STOMP)与前端通信。如果前端收到消息,则必须对其进行处理并更新模块的相应状态(例如标题)。所以如果Angular收到消息,他必须动态选择子组件并更新它的状态(调用children方法)。

这是它在 Vue.js 中的样子:

父组件的内容:

<module ref="moduleA" ></module>
<module ref="moduleB" ></module>
<module ref="moduleC" ></module>

父级负责处理 WebSocket(或 STOMP)通信。在新消息上,他执行以下代码:

const message = JSON.parse(messageFromBackend);
const moduleName = message["module"]; // message["module"] is for example 'moduleB'
this.$refs[moduleName].updateTitle(message["title"]);

因此,当 Parent 收到消息时,他会动态选择合适的孩子(他从后端知道哪个是正确的(message ["module"])),然后更新模块状态。

在 Angular 中可以吗?

标签: angularvuejs2

解决方案


您可以轻松地从父组件访问子组件。只需使用ViewChild属性。子组件类:

export class ChildComponent implements AfterViewInit {
    myAction();
}

在父组件的模板中:

<child-component #child1 ></child-component>
<child-component #child2 ></child-component>
<child-component #child3 ></child-component>

在父组件类中:

export class AppComponent implements AfterViewInit {
    @ViewChild(ChildComponent) child1: ChildComponent;
    @ViewChild(ChildComponent) child2: ChildComponent;
    @ViewChild(ChildComponent) child3: ChildComponent;

    executeOnChildren() {
        this.child1.myAction();
        this.child2.myAction();
        this.child3.myAction();
    }
}

或者根据您的需要,您可以使用 @ViewChildren属性:

export class AppComponent implements AfterViewInit {
    @ViewChildren(ChildComponent) children: QueryList<ChildComponent>;

    executeOnChildren() {
        for(const child of this.children) {
            child.myAction();
        }
    }
}

https://angular.io/api/core/ViewChild https://angular.io/api/core/ViewChildren


推荐阅读