Angular 4 Reactive Form启用字段刷新页面后

时间:2017-11-28 18:58:23

标签: javascript angular angular4-forms reactive-forms

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

}

2 个答案:

答案 0 :(得分: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()
}

答案 1 :(得分:0)

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

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

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