html - 将数组从父组件传递给子角度
问题描述
我有 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>
如何发送此数组并将其用作方法中的参数?
解决方案
只需使用@input 而不是输出。并且当输入值被修改时,使用ngOnChanges
来捕获更改。
child component
export class MonthHeaderComponent implements OnInit {
@Input monthsList: Date[]
ngOnChanges(){
// catch changes
}
}
在父模板中,传递数组。
<child *ngFor="let selectedMonth of selectedMonths" [monthsList]="monthArr"></child>
推荐阅读
- cmake - 是否可以根据cmake中的环境变量制作目标共享库文件名变量?
- python - Python-Django csv.writer
- python - 使用 jinja 在表格单元格中嵌套超链接
- file-upload - 使用 CURL 上传 PHP 图像
- firebase - Firebase + Workspace 附加组件:服务帐户不断过期。无法确定原因
- python - 我不能使用 Try-except
- logback - 未从 logback xml 记录 MDC 值
- android - avc: 拒绝 { module_load }
- javascript - 无法在 react-native WebView 中使用原生 iOS 组件
- javascript - 网站部分低级加密方法