angular - 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 中可以吗?
解决方案
您可以轻松地从父组件访问子组件。只需使用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
推荐阅读
- php - 无法使用保留键返回 Laravel 中的排序数组
- swift - 如何在 Swift Scenekit 中切换对象负载?
- spring-boot - 使用 Spring Security 在一个应用程序中结合数据库和 SAML 身份验证
- internet-explorer - 无法在 Internet Explorer 中打开开发者工具(F12)
- java - Android - 使用 java 对象转换 API JSON 结果以设置不同的设计
- javascript - webpack和TerserPlugin:compress没有开启,但是输出是一行
- python - 需要关于 Beauitful Soup 的帮助,在桌子上重新迭代
- c# - 使用 except Alternative 删除重复项
- reactjs - 将 React 状态变量传递给静态页面进行渲染
- android - 布局文件中的片段会在 Android Studio 中自动加载吗?