将数据从子组件传递到Angular @ViewChild中的父组件,需要2个参数

问题描述

在这里,我尝试使用@Output & EventEmitter@ViewChild & AfterViewInit将数据从子级传递到父级。

这是我的父组件.html文件

<app-child (filterEvent)=" getValuesFromFilters($event)" [name]="name"></app-child>

这是我的父组件.ts文件

name = 'View';
@ViewChild(ChildComponent) child: ChildComponent;
getValuesFromFilters($event) {
  this.criteria = $event;
  console.log(this.criteria);
  this.apply();
}

这是我的ChildComponent .html文件

<button (click)="applyValues()" mat-raised-button>
  Apply
</button>

这是我的ChildComponent .ts文件

export class ChildComponent implements OnInit {
  @Output() filterEvent = new EventEmitter < any > ();
  @input() name: string;

  ngOnInit() {
    console.log(this.name);
  }
  applyValues() {
    this.filterEvent.emit(this.filterValues);
    console.log(this.filterValues);
  }
}

在这里,如果我单击子组件中的“应用”按钮,则在我发出事件时,从子到父的值会出现。但是我想在父级的第一页加载中从子级到父级组件获取值。因此,我正在尝试在父组件中使用@ViewChild。但这给出了这个错误

TS2554:期望有2个参数,但得到1个。core.d.ts(8070,47):未提供“ opts”的参数。

解决方法

请尝试以下操作:

<app-child #Child (filterEvent)=" getValuesFromFilters($event)" [name]="name"></app-child>
@ViewChild("Child",{ static: true }) child: ChildComponent;