首页 文章

以角度2在两个子组件之间进行通信

提问于
浏览
10

我在角度2中非常新 . 我在两个组件之间进行通信时遇到问题 . 当我有一个父项和一些子组件的布局时,可以很容易地使用@Input注释设置子组件的变量 .

但是现在我有一个父组件的布局(主要用于布局)和两个子组件:

example Layout

子组件2有一堆按钮,只创建一个简单的消息 . 现在我想在子组件1中显示此消息 .

我该如何解决?提前致谢

4 回答

  • 7

    您可以使用 @ViewChild@Output 更新子组件中的属性 .

    或者,您可以使用 @Input 代替 @ViewChild .

    seidme建议的方法也可以正常工作 . 这取决于您的使用案例 .

    使用 @ViewChild@Output 的示例:https://plnkr.co/edit/r4KjoxLCFqkGzE1OkaQc?p=preview

    使用 @Input@Output https://plnkr.co/edit/01iRyNSvOnOG1T03xUME?p=preview的示例

  • 8

    除了使用 @Input / @Output 和父组件作为'bridge'的解决方案之外,常见的方法也是引入共享服务 . 该服务需要在父组件中提供,以便子级可以共享该服务的单个实例(How do I create a singleton service in Angular 2?) .

    使用BehaviorSubject as a delegate的基本示例:

    @Injectable()
    export class SharedService {
    
        messageSource: BehaviorSubject<string> = new BehaviorSubject('');
    
        constructor() { }
    }
    

    子组件1:

    export class ChildComponent1 {
    
        constructor(private _sharedService: SharedService) { }
    
        sendMessage(): void {
            this._sharedService.messageSource.next('Hello from child 1!');
        }
    }
    

    子组件2:

    export class ChildComponent2 {
    
        constructor(private _sharedService: SharedService) {
            this._sharedService.messageSource.subscribe((message: string) => {
                console.log('Message: ', message); // => Hello from child 1!
            });
         }
    }
    

    也看到这篇文章:Angular2 - Interaction between components using a service

  • 15

    一种简单的方法是在子组件2中将@Output的输出设置为eventemitter,并在单击按钮时发出一个事件,并将消息作为数据传递 . 然后,在父组件中侦听此事件,并更新在事件发生时设置为子组件1的输入的属性 .

    下图是一个清楚显示机制的示例

    Component-IO

  • 7

    您可以使用模板变量来引用兄弟姐妹:

    <child1 #child1></child1>
    <child2 (someOutput)="child1.doSomething($event)"></child2>
    

相关问题