Angular 2 Component变量未在导入组件中调用的函数中更新

时间:2017-10-23 15:00:23

标签: javascript angular

我正在使用Component1,我将Component2导入到Component1的html中,并将Component1函数(component1.function2())传递给它。

我的问题是,当该函数更改Component1变量时,它不会在Component1范围内显示。所以component1.function2()读取 Component1对象及其中的值,但它不能

这是我的代码:

HTML:

<!-- Component 1, the main component --> 
<div>
    <h2>{{ component_variable }}</h2> defined in Component1 

    <button (click)="change_var()">Change Variable</button> <!-- Changes the value of component_variable successfully -->

    <!-- Component2. Notice change_from_component2(), defined in Component1  -->
    <angular4-paystack
        [key]="public_key"
        [email]="email"
        [amount]="amount"
        [ref]="ref"
        [class]="'btn btn-success'"
        (callback)="change_from_component2($event)"
        >Pay Now</angular4-paystack>
</div>

JS:

/*
  Component1.js
*/
export class Component1 implements OnInit {

//defines a bunch of variables including:
component_variable: any = "Something good";

//skipping past constructors and a bunch of other things

change_var(){
   this.component_variable = "Something better";   //works
}
change_from_component2(e){
   //when this is called from component2, none of the changes made reflects in the component1 scope
   console.log(this.component_variable); // 'Something good', except if you've clicked the Change Variable, then 'Something Better'.
   console.log(this); // logs Component1 object. So it definitely sees Component1

   this.component_variable = "Something even better";   //doesn't work, this function doesn't touch Component1
}

如何实现此更改?

0 个答案:

没有答案