简体   繁体   中英

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.

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. They should be updating. ngStyle is working fine, it's the variable that is not being updated.

I've implemented the similar code

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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