首页 > 解决方案 > 将数组从父组件传递给子角度

问题描述

我有 2 个组件:父母和孩子。当我单击一个按钮(从父组件)并generate()为数组中的每个对象(在子组件中)调用一个函数时,我想将一个数组从父组件发送到子组件。我已经尝试过,@Output() EventEmitter但我不确定这种方法。

父组件

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

    selectedMonths: any[];

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

子组件

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

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

}

并在父 html

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

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

如何发送此数组并将其用作方法中的参数?

标签: htmlangular

解决方案


只需使用@input 而不是输出。并且当输入值被修改时,使用ngOnChanges来捕获更改。

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

   ngOnChanges(){
      // catch changes
   }
 }

在父模板中,传递数组。

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

推荐阅读