【问题标题】:Pass data from child component to parent component in Angular @ViewChild Expected 2 arguments在 Angular @ViewChild 中将数据从子组件传递到父组件 预期 2 个参数
【发布时间】:2021-02-01 19:38:10
【问题描述】:

在这里,我尝试使用 @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”的参数。

【问题讨论】:

    标签: angular typescript angular-components viewchild angular-event-emitter


    【解决方案1】:

    请试试这个:

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

    【讨论】:

    • 在这里我试图在ngAfterViewInit() { this.criteria = this.child.filterValues; console.log(this.criteria);} 中从子级获取值到父级,但父级在子级之前加载
    • 首先它在ngAfterViewInit() 中打印值,然后在子组件值处理之后。因此this.criteria 为空。我想在子组件值处理后获取父组件的值
    猜你喜欢
    • 1970-01-01
    • 2017-08-30
    • 2018-12-24
    • 2020-04-05
    • 2017-06-25
    • 2016-10-25
    • 2019-02-27
    • 2017-04-20
    相关资源
    最近更新 更多