1

I have an Angular component that receives an @Input() property from a parent component. The parent component fetches data asynchronously (from an API), and when the data is set, ngOnChanges should update my local component variables.

However, my variables remain null even after the data is received and ngOnChanges is triggered.

import { Component, Input, OnChanges, SimpleChanges } from '@angular/core';

@Component({
  selector: 'app-invoice',
  templateUrl: './invoice.component.html',
  styleUrls: ['./invoice.component.css']
})
export class InvoiceComponent implements OnChanges {
  invoiceId: string | null = null;

  @Input()
  invoiceData: any = null;

  ngOnChanges(changes: SimpleChanges): void {
    if (changes['invoiceData'] && changes['invoiceData'].currentValue) {
      this.invoiceId = this.invoiceData?.invoiceGenInfo?.invoice?.id;
      console.log("Updated invoiceData:", this.invoiceId); //this works
    }
  }

  onEdit(): void {
    console.log("Invoice Data in Edit:", this.invoiceId);
  }
}

Above is the angular component of the code. The console.log in the ngOnChange method does print the value after a few seconds since it's asynchronous. But even after I see the console value when I trigger onEdit() with a click from a template the console logs as null.

How can I fix this? I need to update the template with the data from the invoiceData object after the API from the parent is completed.?

Thanks

1
  • angular version? Commented Feb 3 at 16:51

1 Answer 1

2

Instead of ngOnChanges just compute the value you want using a get method, it is more reliable than ngOnChanges.

You can also use ChangeDetectionStrategy.OnPush for better performance.

import { Component, Input, OnChanges, SimpleChanges, ChangeDetectionStrategy } from '@angular/core';

@Component({
  selector: 'app-invoice',
  templateUrl: './invoice.component.html',
  styleUrls: ['./invoice.component.css'],
  // changeDetection: ChangeDetectionStrategy.OnPush,
})
export class InvoiceComponent implements OnChanges {

  @Input()
  invoiceData: any = null;

  get invoiceId(): string | null  {
      return this.invoiceData?.invoiceGenInfo?.invoice?.id || null;
  }

  onEdit(): void {
    console.log("Invoice Data in Edit:", this.invoiceId);
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

While using a getter (invoiceId) is a good approach to ensure the latest value is always used and to avoid ngOnChanges, you should also explicitly set changeDetection: ChangeDetectionStrategy.OnPush as well for it to fully be effective for performance.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.