@ViewChild ERROR TypeError: Cannot read properties of undefined (reading 'x') Angular 13.2.5

Viewed 317
import { Component, Input, OnInit } from '@angular/core';
import { FormGroup, AbstractControl } from '@angular/forms';
import { FamilleCouple } from 'src/app/FamilleCouple';

@Component({
  selector: 'app-marie',
  templateUrl: './marie.component.html',
  styleUrls: ['./marie.component.css'],
})
export class ChildComponent implements OnInit {
  x = 5;

  constructor() {}

  ngOnInit() {}
}

@Component({
  selector: 'app-condidature',
  templateUrl: './condidature.component.html',
  styleUrls: ['./condidature.component.css'],
  providers: [],
})
export class ParentComponent implements OnInit {
  @ViewChild(MarieComponent) x!: ChildComponent;
}

I can't get the value of x from the child component in the Parent Component??

How to pass data from the child Component to the parent component using @ViewChild. Console :

1 Answers

Use @Output() decorator for emitting an event value from your child component to his parent.

For example:

Child Component

<button (click)="sendNumber()"></button>
import { Output } from '@angular/core';

@Component({
  selector: 'app-marie',
  templateUrl: './marie.component.html',
  styleUrls: ['./marie.component.css']
})
export class ChildComponent {
  x = 5;
  @Output() valueX = new EventEmitter<number>();

  sendNumber() {
    this.valueX.emit(this.x);
  }
}

Parent Component

<app-marie (valueX)="onValueX($event)"></app-marie>
 @Component({
  selector: 'app-condidature',
  templateUrl: './condidature.component.html',
  styleUrls: ['./condidature.component.css']
})
export class ParentComponent {
  onValueX($event: number) {
    console.log('The value of X: ', $event);
  }
}
Related