What to do when ngOnChanges does not detect a change?

Discussão em 'Angular' iniciado por Fritz Hollnbuchner, Fevereiro 26, 2025.

  1. I am using Angular 18.

    I have an array of "containers" containing, beside other info, an array of "products" each. I use @for to show a container-component for each container, and within those, I use @for to show a product-component for each product.

    In my product component, I want to react to changes in the product, so I use ngOnChanges. However, ngOnChanges does not trigger when I edit my product - probably because it's still the same object, not completely replaced.

    If I use @if(product.someParameter) or even just {{product.someParameter}} it WILL show changes immediately, but still not trigger ngOnChanges. Calling ngOnChanges manually (using a button within the component) works as expected though. I tried using a setter method, but that did not change anything.

    Note: I understand WHY ngOnChanges does not trigger (I think). But I'm wondering what to do now.

    I can think of three solutions for my problem: A) replace the entire product whenever something changes B) create another Input on the product component on a number I can count up whenever I change anything, to trigger ngOnChanges seperately C) use the part of "product" I want to change as a seperate input on my product component to make sure ngOnChanges is triggered

    None of them seem clean, so I wonder if there is a better way to manually tell Angular that something changed, or to trigger a code snippet in the component just by changing something outside.

    If you need to know the usecase: I have one input-field for a barcode-scanner, that can scan containers, products and charges. Anything scanned needs to be added and displayed, with charges being shown as a dropdown. That's why I can't just refer to the properties directly and need to set the value of the dropdown via code.

    Continue reading...

Compartilhe esta Página