0

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 Answers 2

1

You have to initialize the array in your parent component:

array: [] = [];
Sign up to request clarification or add additional context in comments.

Comments

0

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

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.