简体   繁体   English

从父组件调用时,角子组件变量未更新

[英]Angular child component variable not updating when called from parent component

I am having issues dynamically updating an elements style. 我在动态更新元素样式时遇到问题。

I am overlaying some margins on top of an image. 我在图像上方叠加了一些边距。 I created a child component to handle this. 我创建了一个子组件来处理此问题。 I call a function on my child component which calculates the margins and then sets a variable. 我在子组件上调用一个函数,该函数计算边距,然后设置一个变量。

Here is the parent component call, which is triggered by a button click. 这是父组件调用,它是通过单击按钮触发的。

showMargins() {
    if (this.showingMargins) {

        this.showingMargins = false;
    } else {
        this.showingMargins = true;
        this.marginComponent.calculateMargins();
    }
}

And here is my child component: 这是我的孩子部分:

marginStyles: any = {};
...
calculateMargins() {
    //logic 
    ...
    //set the property
    this.marginStyles = {
       'height.px': height,
       'margin-left.px': left
    }
}

And then in my template 然后在我的模板中

<div id="margin-left" [ngStyle]="marginStyles">

I've tried using a function as well 我也尝试过使用函数

private leftDiv() {
    debugger;
    return this.marginStyles;
}

thus changing my template to 因此将我的模板更改为

<div id="margin-left" [ngStyle]="leftDiv()">

but to no avail. 但无济于事。 If I hardcode the values when I declare the variable it works fine. 如果在声明变量时对值进行硬编码,则可以正常工作。

    marginStyles: any = {'height.px': 200, 'margin-left.px': 20};

And if I hardcode it in the template it works fine as well; 如果我在模板中对其进行硬编码,它也可以正常工作; it's just failing after I've done my calculations and won't render the lines that I'm overlaying. 在完成计算之后,它只是失败了,并且不会渲染要覆盖的线条。 Where have I gone wrong? 我哪里出问题了? If it helps, I'm on Angular 4. 如果有帮助,我将使用Angular 4。

Edit: I moved all of my logic to my parent component, and everything looks fine. 编辑:我将所有逻辑移到了父组件,一切看起来都很好。 It appears to me that the values I am for marginStyle are not being updated in the child component, which is baffling to me. 在我看来,我为marginStyle设置的值未在子组件中更新,这让我感到困惑。 They should be updating. 他们应该更新。 ngStyle is working fine, it's the variable that is not being updated. ngStyle工作正常,它是未更新的变量。

I've implemented the similar code 我已经实现了类似的代码

https://stackblitz.com/edit/angular-cvayak https://stackblitz.com/edit/angular-cvayak

and it seems to be working as expected. 它似乎按预期工作。 Please, check for the differences. 请检查差异。 Pay attention to the Element referencing by means of ViewChild decorator, all functions should be public, ElementRef type is the referencing component class because of typization. 注意通过ViewChild装饰器进行的Element引用,所有功能都应该是公共的, ElementRef类型的原因, ElementRef类型是引用组件类。

我认为您应该返回marginStyles而不是leftMarginStyles

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM