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

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

问题描述

我有这个代码...这是我正在尝试构建的示例教程应用程序,它反映了开发人员的日常需求.实际上,当用户在父组件上键入fire"时,子组件会执行一个事件,该事件将booom"这个词发送给父组件 - 这是一个示例,用于演示使用 @Input 和父组件发送消息的子组件之间的通信OnChanges.

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.

现在,我正在尝试做一些不同的事情:当用户按下回车键(keyCode == 13)时,父母应该如何告诉孩子一条像目标锁定"这样的消息给孩子.有了这个,我们将有一个组件之间2路通信的场景.

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.

最好的方法是什么?

子组件

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 !!!");
    }
}
}

父组件

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" ...

然后,每当您更改父组件中 someParentProperty 的值时,Angular 更改检测都会将新值传播给子组件:

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
};

如果你想让孩子在输入属性值改变时执行一些逻辑,在孩子中实现ngOnChanges().

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

  • 使用一个带有 Observable 的共享服务,并让孩子 subscribe()可观察的,或
  • 使用随机值对消息进行前缀或后缀,并使用 | 或其他一些您可以拆分的字符将其与消息分开,以便在子级中您可以轻松地提取消息.
  • 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.

您还可以在共享服务中使用 Subject 而不是 Observable:参见 父母和孩子通过服务进行交流.

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

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

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