Home > OS >  How to declare a variable with a return method as value in Angular?
How to declare a variable with a return method as value in Angular?

Time:12-14

I am using [ngModel] to save the value of a selected option on Angular, but the default value has to be an existing option I can retrieve with this method

getPersonnageByIdd(id: string) {
    const persoSelectionne = this.personnages.find((x: { id: string; }) => x.id === id);
    return persoSelectionne;
  }

The problem is if I declare a variable with the return of that method as value like so

persoDefault = this.getPersonnageByIdd("demochar").name;

The whole component crashes! I have not found an answer for this after a good deal of research, please help. Regards,

I can put the method directly in [ngModel] and the default works, but I need to keep track of the selected option and I would need a variable to do so.

CodePudding user response:

I guess this.personnages does not have the element demochar. In this case, find and getPersonnageByIdd returns undefined.

One solution is to use optional chaining.

persoDefault = this.getPersonnageByIdd("demochar")?.name;

CodePudding user response:

From the code you have provided, there is no attribute called "name" in the result provided by getPersonnageByIdd().

This is how I would go about it

// Assuming that the current component has all the people loaded into an array called peopleList. You want to return the age of the Person which you have found by their id.
getPersonAgeById(id: number) {
    Person foundPerson = this.peopleList.find(x => x.id === id)
    return foundPerson.age; // also assuming that the Person object has an attribute called age of with the type number.
}

Also some suggestions:

  • Proper naming for classes, functions, variables is quite important to be able to keep track of everything.
  • It is unusual to use a string for "id"s (Although in this case it is hard to make a judgment based on the amount of code you provided. Feel free to share the accompanying classes with us)
  • Related