0

In my child.component I have a serivce call that returns an array of objects, invoiceRes, and I assign it to a global variable. Looks like this:

  invoiceCases;

    this.casesService.getCaseByInvoice(invoice.invoiceNumber)
    .subscribe(invoiceRes => {
      this.invoiceCases = invoiceRes;
    },
    err => {
      console.log(err);
    })

In my parent component I am trying to catch the update of this variable with ngOnChange(), which looks like:

@Input() invoiceCases;

ngOnChanges(event) {

 if (event.invoiceCases) {
   this.casesCheck();
 }
}

However ngOnChange is not catching that invoiceCases is assigned the array from the response on the service call.

Any help would be much appreciated.

3
  • can you post your template too Commented Jun 12, 2018 at 18:12
  • @Input is used to communicate from parent to child, not the other way around Either u use service or @output Commented Jun 12, 2018 at 18:15
  • I was planning on assigning invoiceCases to a different array in the parent component to then do looping, etc. So I don't have any direct reference to invoiceCases in my html Commented Jun 12, 2018 at 18:15

2 Answers 2

1

Based on the question and comments you provided, you are trying to pass event from child to parent, in this case you can handle in two ways

(i) Use a shared service, which is managed as a single instance. So if each of the components access the service, they will access the same shared data.

(ii) Use @output event emitter if they are depend on each other (immediate relation)

Sign up to request clarification or add additional context in comments.

1 Comment

went with the shared service and using a behaviorSubject. Thanks for the help and direction.
0

As a couple other users have mentioned, it sounds like you need to use the @output emitter inside the parent component.

export class ParentComponent {
  @Output() public invoiceCases;
}

Then inside your child component, you can use the input property

export class ChildComponent {
  @Input() public invoiceCases;
}

The other part to your question may be a problem with detection of changes. ngOnChanges will only detect shallow changes within your array. So, if a specific property on an object inside your array changes, you may want to use ngDoCheck instead (inside your child component).

private differ: KeyValueDiffer<any, any>;    
constructor(private differs: KeyValueDiffers){
  this.differ = differs.find({}).create();
}

public ngDoCheck() {
  const changes = this.differ.diff(this.invoiceCases);
  if (changes) {
    this.casesCheck();
  }
}

Comments

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.