Receiving an error in Angular 7: Unable to retrieve value from child component as it is returning Undefined

I am looking for a way to transfer a value between components so that I can switch from a list of candidates to another panel where I can edit the selected candidate.

Unfortunately, I encountered an error: ERROR TypeError: "this.listCandidateComponent is undefined" in my edit-candidate component when trying to log the candidate 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() {
  }

Do you have any insights on why this might be happening?

Answer №1

Redirecting you to an edit page..

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

In this case, using ViewChild is not possible.

You need to include parameters in your router.navigate like

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

and in your edit component, make sure to access the queryParams

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

}

Now simply retrieve your candidate with the provided id in your edit component and you're done :)

If you have placed Viewchild in your edit component and wish to load the List component with it, there should be something like below in edit-candidate.component.html

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

Otherwise, it will remain undefined since the list component is not a child of the edit component.

I hope this explanation helps - apologies if I misconstrued your issue (:)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a way to specify a custom error type for returned data in rtk query?

Encountered a type error while using rtk query with the following content : Property 'data' does not exist on type 'FetchBaseQueryError | SerializedError'. Property 'data' does not exist on type 'SerializedError' ...

Utilizing aria-role in Material UI's <Icon> component for enhanced accessibility

I've been using Material UI's <Icon /> component and came across a reference in their documentation about being able to use role="img", which is mentioned here: https://material-ui.com/components/icons/#semantic-svg-icons. However ...

Playing around with Segment Analytics testing using Jest in TypeScript

I've been struggling to write a unit test that verifies if the .track method of Analytics is being called. Despite my efforts, the test keeps failing, even though invoking the function through http does trigger the call. I'm unsure if I've i ...

Issue encountered with the signature provided for a Safe API POST request

Watch this demonstration video of the issue at hand: I have created a signer using my Metamask Private Key and generated a signature from it as shown below: const signer = new ethers.Wallet(PRIVATE_KEY as string, provider) const safeInstance = new ethers. ...

bringing TypeScript functions into another file

I am attempting to include a function in my main.ts file, but I keep encountering errors like 'is not a module' or 'unexpected import token' when I try to execute my file using node main.ts. These functions are not part of any node mod ...

How can you reposition a component within the dom using Angular?

Just started learning Angular, so I'm hoping this question is simple :) Without getting too specific with code, I could use some guidance to point me in the right direction. I'm currently developing a small shopping list application. The idea i ...

Creating an interactive Floating Action Button in Nativescript Angular

Currently, I am incorporating Nativescript Angular into my project. I am interested in implementing a floating action button similar to the one showcased in this plugin. However, I am unsure of how to integrate it within my Nativescript Angular applicatio ...

What is the reason for the HTTP service being activated automatically?

Utilizing the Http service, data is fetched and then passed into the cached service. The component subscribes to the cached service and initiates the HTTP request. The HTTP GET service is intended to be called when the user clicks on an anchor tag. Upon c ...

arrange the css styles in angular

Currently working with Angular and looking to adjust the CSS specificity on the webpage displayed in the link below: https://i.sstatic.net/X3MHW.png The goal is to load 2 before 1. Any suggestions on how to achieve this? ...

How to create an array of objects in Angular 2

Can someone please help me understand how to set up an array of objects so that I can add items to it later on? Here's what I currently have: tab: [{tel:number, name:String}]; ...

What is the best way to incorporate Tradingview's JavaScript into the render function of a React Typescript

I'm trying to incorporate some widgets into my Typescript React component. Here is the embed code export default class App extends React.Component { render(): ReactNode { return ( <div> Chart test <div className= ...

When conducting evaluations, what methods can I use to distinguish between various occurrences of the identical child component?

I currently have a form containing two instances of the same component, similar to the scenario where you input a "From Date" and a "To Date". Currently, I am using: const myComponents = fixture.debugElement.queryAll(By.directive(MyComponent)) const first ...

Displaying JSON Object in Kendo UI Grid with Incorrect Format

I encountered an issue where a function that I passed to a Kendo Grid field in the fetch method returns perfectly on console.log, but only [object Object] is returned in the Kendo Grid display. Here's the background: I am utilizing two services - Rev ...

"Utilize a loop in Angular 2 to consistently send HTTP GET requests to service

Hello, I'm new to working with Angular. Currently, I have an array of product IDs and I would like to make HTTP GET requests based on each ID in the array using a loop. Can someone assist me with this task? Service : addedProductIdArray : string[] = ...

Angular 5 Material Datepicker: A Sleek and Efficient Way to

I want the Angular Material Datepicker to remain open by default when the page is loaded, appearing within a section without needing to be triggered by an input field click. Currently, I am using a Datepicker that necessitates clicking on an input field. ...

Activate a function with one event that is triggered by another event in Angular 5 and Material Design 2

I am facing an issue where I need to change the value of a radio button based on another radio button selection in Angular 5 with Material Design 2. However, the event is not triggering and there are no console errors being displayed. For example, if I cl ...

Updating user attributes as an administrator using the Cognito SDK

Currently, I am in the process of developing an Angular application and I aim to integrate authentication using AWS Cognito (my experience with AWS is fairly limited). So far, I have successfully incorporated features such as sign-up, sign-in, sign-out, MF ...

Issue with Radio Button Value Submission in Angular 6 and Laravel 5.5

I developed a CRUD application utilizing Angular and Laravel 5.5. Within this application, I included three radio buttons, but encountered an error when trying to retrieve their values... A type error occurred indicating it was unable to read the data t ...

Utilizing Dynamic Components and the Event Emitter Feature in Angular Version 5

As a newcomer to Angular, I am currently grappling with the concept of dynamic components within my project. Specifically, I am working on implementing functionality where a user can select a row in a component and then click a button to open a modal (cont ...

Tips for accurately inputting a global object with an index

I'm in the process of converting a large monolithic JavaScript application to TypeScript and am facing an issue regarding typing a specific module. I am seeking guidance on how to approach this particular problem. It's important to note that I d ...