I have a reactive from declared in angular 4
this.userForm = this.fb.group({
"id": [user ? user.id : ""],
"profile": this.fb.group({
"email": [user && user.profile.email ? { value: user.profile.email, disabled: true } : "", Validators.compose([Validators.required, Validators.email])],
}),
"username": [user && user.username ? { value: user.username, disabled: true } : "", Validators.compose([Validators.required, GlobalValidator.usernameFormat])],
})
By default if my form is filled out with the data the form field is disabled (email, username). The problem that I am facing is, If I refresh my page the form field appears enabled.
(EDITED)
ngOnInit() {
this.buildForm()
if (this.activatedRoute.snapshot.params.id) {
this.service.getUser(Number(this.activatedRoute.snapshot.params.id)).subscribe((user) => {
this.buildForm(user)
})
}
}
buildForm(user?:any){
this.userForm = this.fb.group({
"id": [user ? user.id : ""],
"profile": this.fb.group({
"email": [user && user.profile.email ? { value: user.profile.email, disabled: true } : "", Validators.compose([Validators.required, Validators.email])],
}),
"username": [user && user.username ? { value: user.username, disabled: true } : "", Validators.compose([Validators.required, GlobalValidator.usernameFormat])],
})
}
to fix this issue I change my code :
before:
"username": [user && user.username ? { value: user.username, disabled: true } : "", Validators.compose([Validators.required, GlobalValidator.usernameFormat])],
after:
this.userForm = this.fb.group({
username : this.fb.control("")
})
if(user){
this.userForm.get("username").setValue(user.username)
this.userForm.get("username").disable()
}