1
votes

I have 2 components: parent and child. I want to send an array from parent to child when I click on a button(from parent-component) and call a function generate() for every object in array(in child-component). I have tried something with @Output() EventEmitter but I am not sure of this approach.

parent component

export class ViewCalendarsComponent implements OnInit {
    @ViewChildren(MonthHeaderComponent) months: any[];
    @Output() monthsList: EventEmitter<Date[]> = new EventEmitter();

    selectedMonths: any[];

    test() {
        this.monthsList.emit(this.selectedMonths);
    }
}

child component

export class MonthHeaderComponent implements OnInit {
    ngOnInit() {
    }
    generate(date: Date) {
        // code here....
    }

    show() {
        for (let i = 0; i <= monthsList.length; i++)
        {
            generate(monthsList[i]);
        }
    }

}

and in parent html

<button class="primary" (click)="test()"> Show </button>

  <div class="right view-calendar">
          <child *ngFor="let selectedMonth of selectedMonths" [monthsList]="show($event)"></child>
        </div>

How can I send this array and use it as parameter in a method?

1
@Output shoots things from the child to the parent. Since you want functionality in the parent to pass information to child, you would use @Input - rhavelka

1 Answers

1
votes

Just use the @input instead of output. And when the input value get modifies, use the ngOnChanges to catch the changes.

 child component
 export class MonthHeaderComponent implements OnInit {
    @Input monthsList: Date[]

   ngOnChanges(){
      // catch changes
   }
 }

In the parent template, pass the array.

<child *ngFor="let selectedMonth of selectedMonths" [monthsList]="monthArr"></child>