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
)}
- 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?
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,
Additional
()
at the end of funtion wrapped inside()
will declare and call the function.see more about anonymous function