Angular 6:如何在动态创建的组件之间实现双向通信
创始人
2024-10-16 13:00:24
0

在Angular 6中,可以使用@Input@Output装饰器来实现动态创建组件之间的双向通信。

以下是一个示例,演示了如何在动态创建的组件之间实现双向通信:

首先,创建一个动态组件ChildComponent,其中包含一个输入属性message和一个输出属性messageChange

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

@Component({
  selector: 'app-child',
  template: `
    
  `
})
export class ChildComponent {
  @Input() message: string;
  @Output() messageChange: EventEmitter = new EventEmitter();

  onMessageChange() {
    this.messageChange.emit(this.message);
  }
}

然后,创建一个父组件ParentComponent,在该组件中创建子组件ChildComponent的实例,并在父组件中处理子组件的messageChange事件:

import { Component } from '@angular/core';
import { ChildComponent } from './child.component';
import { ComponentFactoryResolver, ViewContainerRef } from '@angular/core';

@Component({
  selector: 'app-parent',
  template: `
    
` }) export class ParentComponent { childComponentRef: any; constructor(private resolver: ComponentFactoryResolver, private container: ViewContainerRef) {} createChildComponent() { const childComponentFactory = this.resolver.resolveComponentFactory(ChildComponent); this.childComponentRef = this.container.createComponent(childComponentFactory); this.childComponentRef.instance.message = 'Hello from parent component'; this.childComponentRef.instance.messageChange.subscribe((message: string) => { console.log('Message from child component:', message); }); } }

在上面的示例中,我们首先使用ComponentFactoryResolverViewContainerRef来创建ChildComponent的实例,并将其添加到父组件的#childContainer子元素中。

然后,我们通过this.childComponentRef.instance.message来设置子组件的输入属性message的值。

最后,我们通过订阅子组件的messageChange事件来监听子组件的输出属性messageChange的变化,并在父组件中处理该事件。

使用上述代码示例,当点击“创建子组件”按钮时,将创建一个子组件,并将父组件中的文本输入框中的值传递给子组件。当在子组件中更改文本输入框的值时,父组件会打印出子组件的新值。

希望对你有所帮助!

相关内容

热门资讯

一分钟秒懂!wepoker辅助... 一分钟秒懂!wepoker辅助器有哪些功能,wepoker免费脚本咨询,玩家教你(有挂攻略)准备好在...
玩家必看科普!wepoker轻... 玩家必看科普!wepoker轻量版透视方法,拱趴大菠萝自动计算机器人,新2025教程(有挂攻略)准备...
科普常识!佛手大菠萝有挂吗,w... 科普常识!佛手大菠萝有挂吗,wepoker辅助透视,分享教程(有挂透视);佛手大菠萝有挂吗软件透明挂...
推荐十款!wepoker软件安... 推荐十款!wepoker软件安装包,wepokerplus辅助,可靠教程(有挂透明);支持多人共享记...
关于!wejoker辅助器怎么... 关于!wejoker辅助器怎么卖,hhpoker是内部控制吗,2025新版技巧(有挂透视)1、很好的...
技术分享!wepoker私人局... 这是一款非常优秀的wepoker私人局透视插件 ia辅助检测软件,能够让你了解到wepoker私人局...
指导大家!pokemmo手机辅... 指导大家!pokemmo手机辅助软件,hhpoker有没有作弊辅助,系统教程(有挂方法)1、很好的工...
科技通报!拱趴大菠萝万能挂,w... 科技通报!拱趴大菠萝万能挂,wepoker-h5下载,AI教程(有挂技巧)1、点击下载安装,微扑克w...
玩家攻略!wepoker辅助器... 1、玩家攻略!wepoker辅助器安装包,wepoker俱乐部辅助器,细节揭秘(有挂攻略)(UU p...
一分钟揭秘!大菠萝免费辅助,w... 一分钟揭秘!大菠萝免费辅助,wepoker免费透视,新版2025教程(有挂教程);支持2-10人实时...