4
votes

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])],
    })

}

2
I'd suggest providing a bit more context so we can see where you're running everything. Also, it helps if you make a demo using stackblitz.com. Just click Angular and it creates a project that you can drop in your code and replicate the issue. - mtpultz
Where is this user fetched from? - Chau Tran
Is there any error at the browser's console? - elvin
no, no errors in the console, just after refresh the browser tab, my form fields disabled, appears enabled - Ricardo
@mtpultz Is dificult to reproduce in stackblitz.com because happens if I refresh the browser tab - Ricardo

2 Answers

1
votes

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()
}
0
votes

I had the same problem, but calling this.userForm.get("username").disable() did not fixed it because I was reloading my view (using router.navigate()).

In my case I had to reset my form before reloading:

this.userForm = undefined; this.router.navigate([path]);