1

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
  • 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 Commented Dec 4, 2018 at 14:17

1 Answer 1

1

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>
Sign up to request clarification or add additional context in comments.

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.