Brian Stanley
Brian Stanley

Reputation: 2196

Passing Array with @Input property Angular 5

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.

Upvotes: 0

Views: 782

Answers (2)

CodeCheshire
CodeCheshire

Reputation: 730

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();
  }
}

Upvotes: 0

Sajeetharan
Sajeetharan

Reputation: 222582

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)

Upvotes: 1

Related Questions