如何通知父组件变量更改到另一个组件? [英] How to notify the parent component variable changes to another component?

查看:83
本文介绍了如何通知父组件变量更改到另一个组件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在应用程序中进行实例化,父组件中有很多组件.

I am doing the internatiolization in the application , There are many components inside the parent component.

在app.component.ts中,我将当前选择的货币设置如下,

In app.component.ts, i am setting the current selected currency as follows,

 ngOnInit() {      
    this.selectedLanguage = "EN";
    this.selectedCurrency = "EUR";
    //also setting to local storage
    localStorage.setItem('currency', this.selectedCurrency);
}

还有另一个子组件,我必须在管道中使用 selectedcurrency ,所以我得到的 selectedcurrency 如下

There is another child component where i have to use the selectedcurrency in the pipe , so i am getting the selectedcurrency in as follows

export class EveComponent  implements OnInit {
     selectedCurrency :string;
     ngOnInit() {
         this.selectedCurrency = localStorage.getItem("currency");
     }
}

,但是当父级发生更改时,这似乎不起作用.和我的管道如下,

but this does not seems to work, when changes happening in parent. and my pipe as follows,

 <div class="price">{{123 | currConvert | currency:selectedCurrency:true:'3.2-2'}}</div>

现在,当我在父页面上更改selectedCurrency时,我也希望将其应用于EveComponent.如何使用angular2做到这一点?

Now when i change the selectedCurrency on my parent page, i want that to be applied on the EveComponent as well. How to do that with angular2?

推荐答案

1-如果子组件是appComponent的直接子组件,则您应该可以使用 @Input 在孩子中.

1 - If your child component is the direct child of your appComponent , you should be able to use an @Input in the child.

父组件模板:

   <child-cmp [selectedCurrency]="selectedCurrency"></child-cmp>

然后在子组件内部

export class EveComponent  implements OnInit {
     @Input() selectedCurrency :string;
}

无需再在子级中使用localStorage服务.

no need to to use your localStorage service anymore in child.

2-子组件不是父组件的直接子组件,在这种情况下,您可以创建eventEmitter:

localStorage服务内部:

Inside you localStorage service :

export class LocalStorageService{
    $currencyChanges = new EventEmitter<any>();

    public setItem(item){
        // what ever u where doing , plus : 
        this.$currencyChanges.emit(item);
    }
}

然后在孩子里面,您已经有了服务,因此您可以:

And then inside the child , you've got the service already , so u can :

导出类EveComponent实现OnInit {

export class EveComponent implements OnInit {

 ngOnInit() {
     localStorage.$currencyChanges.subscribe((changes)=>{
         this.selectedCurrency = changes;

     });
 }

这篇关于如何通知父组件变量更改到另一个组件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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