gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 19:27:39 25 4
gpt4 key购买 nike

我有一个在 angular 4 中声明的 reactive from

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

最佳答案

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

之前:

"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()
}

关于javascript - 刷新页面后Angular 4 Reactive Form启用字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47538990/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com