How to make typescript evaluate a fat arrow function explicitly?

165 views Asked by At

I am using a FormBuilder in a angular form.I want to initialize the value of the FormControl based on the response received from a API call to backend (referred as userFormDetails here).

I am trying to use fat arrow function ()=> for the same like :

//Other Form Controls
 empCode:[this.userFormDetails.userId],
 empName:[this.userFormDetails.name],
 pensionType:[''],
 fhName:[
          ()=>{
return this.userFormDetails.gender=="Male"? this.userFormDetails.fatherName:this.userFormDetails.spouseName
}],   
.
//Rest of the controls

However this get evaluated as

function () { return _this.userFormDetails.gender == "Male" ? _this.userFormDetails.fatherName : _this.userFormDetails.spouseName; }

It returns the function itself as the value instead of evaluating it. How can I make the function return the evaluated value?

I also tried doing:

1.

()=>{ ( **<--addition parenthesis**
return this.userFormDetails.gender=="Male"? this.userFormDetails.fatherName:this.userFormDetails.spouseName
)}
  1. Setting value of FormControl as:
fhName:[{
     value: ()=>{
                 return this.userFormDetails.gender=="Male"? 
                 this.userFormDetails.fatherName:this.userFormDetails.spouseName
                },
                disabled:false
             }
            ]

But none of them worked. Can someone guide me the correct method to do this?

2

There are 2 answers

0
Jithin Scaria On BEST ANSWER

You are setting the form control equal to function. you have declared it but you are not calling it, so use as a anonymous function as a closure, like below.

try changing this way,

fhName:[(()=>{
return this.userFormDetails.gender=="Male"? this.userFormDetails.fatherName:this.userFormDetails.spouseName
})()] 

Additional () at the end of funtion wrapped inside () will declare and call the function.

see more about anonymous function

0
Srajan Soni On

As suggested by @Jithin Scaria in the comments, the following method works :

(() => { / content / })() Wrapping the function in parenthesis and then calling it makes TS to compute the value and return it.