0
votes

I am trying to pass an array to a child component. The array is being defined in the subscribe method of a parent component's onInit lifecycle hook.

Parent component:

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'selector-parent',
  templateUrl: 'parent.component.html'
})

export class ParentComponent implements OnInit {

  array: [];

  constructor() { }

  ngOnInit() {
    this.appDataService.getValues()
      .subscribe(
        value => {
          value.item
            .filter(loaded => !this.array.some(existing => existing.key === loaded.key))
            .forEach(loaded => { this.array.push(loaded) })
        }
      )
  }
}

Child component:

import { Component, OnInit } from '@angular/core';

@Component({
  selector: '[selector-child]',
  templateUrl: 'child.component.html'
})

export class ChildComponent implements OnInit {

  @Input() inputArray: [];

  constructor() { }

  ngOnInit() {
    console.log(this.inputArray)
  }
}

Binding is: <tr selector-child [inputArray]="array"></tr>

Unfortunately, the console log on the inputArray is turning up undefined. I've tried using ngOnChanges in the child component but for some reason, it won't recognize the change in the parent. Thinking of using a service to pass the data if there isn't a simpler way to solve the problem.

2

2 Answers

1
votes

You have to initialize the array in your parent component:

array: [] = [];
0
votes

I don't see ngOnChanges in your child component. Also, make sure you do it as how it specified in the angular docs. https://angular.io/guide/component-interaction#intercept-input-property-changes-with-ngonchanges