Angular响应式表单视图值未设置问题(因FormControlName导致)
Angular响应式表单预填充值消失的问题解决
我来帮你梳理下这个问题——这是Angular响应式表单的典型行为,搞清楚逻辑就容易解决啦!
问题原因分析
当你给输入框加上formControlName后,Angular的响应式表单会完全接管这个输入框的状态和值,你写的原生value="{{currentUser.firstName}}"会被表单控件的值覆盖。而你目前的代码里,虽然通过异步请求拿到了currentUser,但并没有把这些值同步到accountForm的FormControl中;再加上异步请求的时序问题,表单初始化时控件是空的,渲染后就把插值的内容清空了。
另外你提到用setValue/patchValue没生效,大概率是因为你调用这些方法的时候,currentUser还没被赋值(异步请求还没返回),或者accountForm还没完成初始化,导致更新操作相当于对空控件赋值,自然看不到效果。
可行的解决方案
1. 先确保表单正确初始化
首先要在组件里初始化accountForm,定义好对应的FormControl:
import { FormGroup, FormControl } from '@angular/forms'; // 在组件类里 accountForm: FormGroup; ngOnInit() { // 先初始化表单 this.accountForm = new FormGroup({ firstName: new FormControl(''), surname: new FormControl('') }); // 再获取用户数据 this.currUserId = this.userId$.value; this.authService .findOne(this.currUserId) .subscribe((user: User) => { this.currentUser = user; // 数据回来后同步到表单 this.accountForm.patchValue({ firstName: user.firstName, surname: user.surname }); }); }
2. 移除input的原生value属性
既然用了响应式表单,就不需要手动写value属性了,FormControl会负责渲染值:
<div class="form-input"> <label>FirstName</label> <input formControlName="firstName" type="text" /> </div> <div class="form-input"> <label>surname</label> <input formControlName="surname" type="text" /> </div>
可选优化:使用Async管道避免手动订阅
如果想简化代码,也可以用Async管道处理异步数据,同时在表单初始化时结合async来同步值:
// 把currentUser改成Observable currentUser$: Observable<User>; ngOnInit() { this.accountForm = new FormGroup({ firstName: new FormControl(''), surname: new FormControl('') }); this.currUserId = this.userId$.value; this.currentUser$ = this.authService.findOne(this.currUserId); // 订阅Observable更新表单 this.currentUser$.subscribe(user => { this.accountForm.patchValue(user); }); }
模板里可以保留*ngIf="currentUser$ | async as currentUser"来确保数据存在再渲染表单。
这样调整后,表单就能正确预填充从数据库拿到的用户数据啦!
内容的提问来源于stack exchange,提问作者Jes
相关产品推荐
相关产品推荐

