Search code examples
angulartypescriptviewchild

Can't access value from child component : Undefined - Angular 7


I want to pass a value betwen components in order to switch from a list of candidates to another panel where i can edit the selected candidate.

Sadly, i get this error : ERROR TypeError: "this.listCandidateComponent is undefined" in my edit-candidate component when i try to log the candidate that i initialized in list-candidate component.

list-candidate.component.html

<table class="table table-striped">
  <tbody *ngFor="let candidate of candidates">
    <td><h4>{{ candidate.id }}</h4></td>
    <td><a class="btn btn-outline-warning btn-sm" style="margin: 1%"
         (click)="getCandidateById(candidate.id)" role="button">Modifier</a>
    </td>
 </tbody>
</table>

list-candidate.component.ts

@Component({
  selector: 'app-list-candidate',
  templateUrl: './list-candidate.component.html',
  styleUrls: ['./list-candidate.component.scss']
})
export class ListCandidateComponent implements OnInit {

  candidate: Candidate;
  candidates: Candidate[];

  ngOnInit() {
    this.getCandidateList();
  }

  async getCandidateById(id: number) {
    const headers = new HttpHeaders({
      'Content-type': 'application/json; charset=utf-8',
      Authorization: 'Bearer ' + this.cookie.get('access_token')
    });
    const options = {
      headers
    };
    await this.httpClient.get(`${this.baseUrl}/${id}`, options)
      .toPromise()
      .then(
        (response: Candidate) => {
          console.log('GET request successful', response);
          this.candidate = response;
        },
        (error) => {
          console.log('GET error : ', error);
        }
      );
    await this.router.navigate(['/candidates/edit']);
   }

edit-candidate.component.ts

@Component({
  selector: 'app-edit-candidate',
  templateUrl: './edit-candidate.component.html',
  styleUrls: ['./edit-candidate.component.scss']
})

export class EditCandidateComponent implements OnInit, AfterViewInit {

  candidate: Candidate;

  @ViewChild(ListCandidateComponent) listCandidateComponent;

  ngAfterViewInit() {
    this.candidate = this.listCandidateComponent.candidate;
    console.log(this.candidate);
  }

  ngOnInit() {
  }

Any ideas why ?


Solution

  • You are routing to an edit page..

    await this.router.navigate(['/candidates/edit']);
    

    You can't use ViewChild in this scenario.

    You have to add params to your router.navigate like

    await this.router.navigate(['/candidates/edit'], { queryParams: { candidateId: id } });
    

    and in your edit component you have to read the queryParams

    id: any;
    constructor(private route: ActivatedRoute) { }
    ngOnInit() {
    this.route.queryParams
      .subscribe(params => {
          this.id = params['candidateId'];
      });
    

    }

    Now just load your candidate with the id in your edit component and you'r finished :)

    You placed Viewchild in your edit component. If you want to load List component with viewchild, anywhere in edit-candidate.component.html has to be something like

    <app-list-candidate> </app-list-candidate>

    else it would always be undefined because list component is not child of edit component.

    I hope it helps - sorry If I misunderstood your problem (: