4

我有一个在角度 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])],
})

默认情况下,如果我的表单填写了数据,则表单字段被禁用(电子邮件、用户名)。我面临的问题是,如果我刷新页面,表单字段将显示为已启用。

(已编辑)

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

}

4

2 回答 2

1

为了解决这个问题,我更改了我的代码:

前:

"username": [user && user.username ? { value: user.username, disabled: true } : "", Validators.compose([Validators.required, GlobalValidator.usernameFormat])],

后:

this.userForm = this.fb.group({
username : this.fb.control("")
})
if(user){
this.userForm.get("username").setValue(user.username)
this.userForm.get("username").disable()
}
于 2017-11-29T19:56:26.470 回答
0

我遇到了同样的问题,但是调用 this.userForm.get("username").disable() 并没有解决它,因为我正在重新加载我的视图(使用 router.navigate())。

就我而言,我必须在重新加载之前重置我的表单:

this.userForm = 未定义;this.router.navigate([路径]);

于 2019-10-07T11:27:49.297 回答