Pass data from child component to parent component in Angular @ViewChild Expected 2 arguments

3k views Asked by At

In here i am trying to pass data using @Output & EventEmitter and @ViewChild & AfterViewInit from child to parent.

This is my parent component .html file.

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

This is my parent component .ts file

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

This is my ChildComponent .html file

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

This my ChildComponent .ts file

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);
  }
}

In here if i click the apply button in child component, values coming from child to parent as i am emitting an event. But i want to get the values from child to parent component on the first page load of the parent. Therefore i am trying to use @ViewChild in parent component. But it gives this error.

TS2554: Expected 2 arguments, but got 1. core.d.ts(8070, 47): An argument for 'opts' was not provided.

1

There are 1 answers

2
Thunderbolt Engineer On BEST ANSWER

Please try this:

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