Issue
Component.ts
@Input() userProfile: any;
constructor(
private formBuilder: FormBuilder,
) {}
ngOnInit() {
this.profile = this.formBuilder.group({
gender: [this.userProfile.gender],
first_name: [this.userProfile.first_name, Validators.required],
last_name: [this.userProfile.last_name, Validators.required],
isd_code: [this.userProfile.phone_number.isd_code],
phone_number: [this.userProfile.phone_number.phone_number],
})
}
Here in userProfile
the phone_number
and child phone_number
and isd_code
are not available initially. So when I try to edit the profile page I'm getting the error
ERROR TypeError: Cannot read property 'isd_code' of null at profileEditComponent.ngOnInit
In html I use the safe navigation operator but here I have to set the values in formbuilder
otherwise the validation fails even if the value is set.
I tried to check if the property is undefined but it doesn't work this.userProfile.phone_number.isd_code != undefined
.
Solution
Use safe navigation operator ?
or ternary operator for typescript
Try like this:
this.userProfile?.phone_number?.isd_code != undefined
In TS:
isd_code: [(this.userProfile)?(this.userProfile.phone_number ? this.userProfile.phone_number.isd_code : null) : null],
Answered By - Adrita Sharma
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.