Search code examples
angulartypescriptobjectangular10

Updating an object using a data which is coming from another component in angular 10


So in my project , I have 3 components. first is the main , secend and third.

I've created an empty object in the main component and passed it into 2 others, and the secend component make some changes and after all the 3rd component shows the changes in a table which is declared to show numbers.

I'm having trouble showing the updated value for displayItmes ={} in the third component.

I'm kind got stuck in here.

export class firstComponent{
  displayItems = {};
}

HTML:

<div class="flex-fill">
    <app-secend [displayItems]="displayItems"></app-secend>
    <app-third  [displayItems]="displayItems"></app-third>
</div>

The secend component is:

 export class secend {
    @Input() displayItems;
    x = _sum;
    syncDisplayItems() {
        this.displayItems.TotalPurchaseAndImport = 15 + x
    }
}

and the third component is :

export class third {
    _displayItems;
    @Input()
    set displayItems(data: any) {
        if (data) {
            this._displayItems = data;
        }
    }

    get displayItems(): any {
        return this._displayItems;
    }
}

and the third component HTML is:

<div class="p-col-3 vat-cell">
 {{ displayItems.TotalPurchaseAndImport}}
</div>

Solution

  • In the secend component SyncDisplayItem method that populate the data isn't called. try to implement ngOnInit and call it from there. I created a stack blitz solution with the same requirements and add extra button to demostrate the change event from second component OnInitand on Button click

    https://stackblitz.com/edit/angular-ivy-cgmkun?file=src%2Fapp%2Fcomponents%2Fsecond.component.ts