角2 - 组件之间的双向通信 [英] Angular 2 - Two way communication between components

查看:145
本文介绍了角2 - 组件之间的双向通信的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个code ......这是我试图构建一个示例应用程序的教程这反映了开发人员的日常需求。
实际上,当用户键入火父组件上,子执行这是发送给父词booom的事件 - 这是一个样本表现出子组件将消息发送到使用@input和一个父组件之间的通信OnChanges。

现在,我尝试做不同的:家长应与一些如何告诉孩子像目标锁定给孩子一个信息,当用户preSS回车键(按键code = = 13)。与此我们将有2个方式的组件之间的通信的情形。

什么是最好的方法呢?

child.component

 进口{组件,输入,OnChanges,EventEmitter,输出,注射}从'angular2 /核心;
@Injectable()
@零件({
选择:儿童分量',
模板:`< P>我的子组件< / P>
`
})
出口类ChildComponent实现OnChanges {
@input()TXT:字符串;
@Output()宗旨:EventEmitter<&任何GT; =新EventEmitter();
ngOnChanges(变化:{[作为propName:字符串]:SimpleChange}){
    VAR T =变化['TXT'] CurrentValue的。
    如果(T =='火'){
        的console.log(火!');
        this.aim.emit(booom !!!);
    }
}
}

parent.component

 进口{}组件从angular2 /核心;
进口{} ChildComponent从'./child.component
@零件({
选择:父组件,
指令:[ChildComponent]
模板:`< P>我父组件< / P>
<输入类型=文本[(ngModel)] =theModel(的keydown)=箭头($事件)>
&所述p为H.;反馈:{{反馈}}&下; / P>
<儿童分量的txt ={{theModel}}(AIM)=反馈= $事件>< /儿童成分>
`
})
出口类为父级{
该模型;
反馈;
箭头(EVT){
    如果(evt.k​​ey code == 13){
        //需要对孩子造成的事件 - 消息像目标锁定
    };
}
}


解决方案

  

我的疑问是关于做相反的方式:捕捉儿童的父的事件。还记得那个孩子永远不会有父母的选择。这就是为什么它是真正的不同。


我觉得困惑是回避的事实,你并不需要一个事件。对于家长和RARR;孩子沟通,只是另一种输入属性添加到孩子。和父母属性绑定到它:

 <儿童成分[anotherInputProperty] =someParentProperty...

然后,只要您在父组件更改 someParentProperty 的值,角度变化的检测将传播新的价值孩子:

 如果(evt.k​​ey code === 13){
    //需要引起孩子的事件 - 就像目标锁定的消息。
    //只要改变属性值:
    this.someParentProperty =一些新的价值;
    //角将传播新的价值对孩子照顾
};

如果您希望孩子执行一些逻辑,当输入属性值的变化,实施 ngOnChanges()中的孩子。

如果该问题是,你不希望每次更改消息,那么你既可以


  • 使用与观测共享服务,并有子订阅()来的观测,或

  • preFIX或随机值postfix的消息,而且从消息有独立的一个 | 或其它字符可以拆分,因此在孩子,你可以很容易地提取消息。

您还可以在共享服务使用一个主题,而不是可观察到的:见<一href=\"https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#bidirectional-service\"相对=nofollow>家长和孩子通过服务沟通。

I've this code...It's a sample tutorial application I'm trying to build that's reflect the daily basis needs of a developer. Actually, when the user types "fire" on the parent component, the child execute an event that's sends to the parent the word "booom" - It's a sample to demonstrate communication between a child component sending messages to a parent component using @Input and OnChanges.

Now, I'm trying to do different: The parent should with some how tell to the child a message like "Target Locked" to the child when the user press the enter key (keyCode == 13). With this we will have a scenario of 2 way communication between components.

What is the best approach ?

child.component

import {Component, Input, OnChanges, EventEmitter,Output, Injectable} from 'angular2/core';
@Injectable()
@Component({
selector: 'child-component',
template: `<p>I'm the child component</p>
`
})
export class ChildComponent implements OnChanges { 
@Input() txt: string;
@Output() aim: EventEmitter<any> = new EventEmitter();
ngOnChanges(changes: {[propName: string]: SimpleChange}) {
    var t = changes['txt'].currentValue;
    if(t == 'fire') {
        console.log('Fire !!!');
        this.aim.emit("booom !!!");
    }
}
}

parent.component

import {Component} from 'angular2/core';
import {ChildComponent} from './child.component'
@Component({
selector: 'parent-component',
directives : [ChildComponent]
template: `<p>I'm the parent component</p>
<input type="textbox" [(ngModel)]="theModel" (keydown)="arrow($event)">
<p>feedback: {{feedback}}</p>
<child-component txt="{{theModel}}" (aim)="feedback=$event"></child-component>
`
})
export class ParentComponent { 
theModel;
feedback;
arrow (evt){
    if(evt.keyCode ==13) {
        //Need to cause an event on the child - a message like "Target Locked"
    };
}
}

解决方案

My doubt is about to do the opposite way: Child capture the event of the parent. Remember the child will never have the selector of the parent. That's why it's really different.

I think the confusion is around the fact that you don't need an event. For parent → child communication, just add another input property to the child. And bind a parent property to it:

<child-component [anotherInputProperty]="someParentProperty" ...

Then, whenever you change the value of someParentProperty in the parent component, Angular change detection will propagate the new value to the child:

if(evt.keyCode === 13) {
    // Need to cause an event on the child - a message like "Target Locked".
    // Just change the property value:
    this.someParentProperty = "some new value";
    // Angular will take care of propagating the new value to the child
};

If you want the child to execute some logic when the input property value changes, implement ngOnChanges() in the child.

If the issue is that you don't want to change the message each time, then you could either

  • use a shared service with an Observable and have the child subscribe() to the Observable, or
  • prefix or postfix the message with a random value, and separate it from the message with a | or some other character you can split on, so that in the child you can easily extract the message.

You can also use a Subject rather than an Observable in the shared service: see Parent and children communicate via a service.

这篇关于角2 - 组件之间的双向通信的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆