简体   繁体   English

将数组从父组件传递给子 angular

[英]pass array from parent component to child angular

I have 2 components: parent and child.我有 2 个组件:父组件和子组件。 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).当我点击一个按钮(来自父组件)并为数组中的每个对象(在子组件中)调用一个函数generate() ,我想从父到子发送一个数组。 I have tried something with @Output() EventEmitter but I am not sure of this approach.我已经尝试过使用@Output() EventEmitter但我不确定这种方法。

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并在父 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?如何发送此数组并将其用作方法中的参数?

Just use the @input instead of output.只需使用@input 而不是输出。 And when the input value get modifies, use the ngOnChanges to catch the changes.当输入值被修改时,使用ngOnChanges来捕捉变化。

 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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM