通知子组件关于Angular2变化 [英] Notify child component about changes in Angular2

查看:124
本文介绍了通知子组件关于Angular2变化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有简单的Angular2组件

Suppose I have simple Angular2 component

@Component({ selector: 'parent' })
@View({
    template: `
        <p>Parent {{ data }}</p>
        <child [model]="data"></child>
    `,
    directives : [Child]
})
export class Parent {
    data: number = 42;
}

,你可以看到它使用另一个简单的组件

as you can see it uses another simple component

@Component({
    selector: 'child',
    properties : ['model']
})
@View({
    template: `
        <p>Child {{ model }}</p>
    `,
})
export class Child {
    model: number;
}

我传递模式组件的孩子投掷角的 [属性] 语法数据绑定。如果我想跟踪模式母公司的一些修改我可以轻松地事件添加到孩子,并抛出了(事件)语法跟踪的父的变化。所以,我如何与相反的情况管理,当修改模式孩子希望收到通知?

I am passing model from the parent component to the child throw the angular's [property] syntax for data-binding. if I want to track some changes of model in the parent I can easily add event to the child and throw the (event) syntax track the changes in the 'parent'. So how I could manage with opposite situation when parent changes model and child want to be notified ?

推荐答案

您可以把您的附加逻辑或计算到的的onChange 方法,那毕竟是组件的绑定属性的更新调用。

You can put your additional logic or calculations into onChange method, that is called after all of component's bound properties are updated.

@Component({
    selector: 'child',
    properties : ['model']
})
@View({
    template: `
        <p>Child {{ model }}</p>
    `,
})
class Child {
    model: number;

    onChange(map){
      if(map.model) {
        console.log('doing crazy stuff here');
        console.log(map.model); //SimpleChange {previousValue: 43, currentValue: 44}
      }
    }
}

Plunker

这篇关于通知子组件关于Angular2变化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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