遇到这个问题的场景是园子博客后台编辑链接的页面,下面是对应 component 的构造函数代码
constructor(
private fb: NonNullableFormBuilder,
) {
this.editLinkForm = this.fb.group({
categoryId: [this.editingDto.categoryId, linkDtoValidators.categoryId],
title: [this.editingDto.title, linkDtoValidators.title],
url: [this.editingDto.url, linkDtoValidators.url],
});
}
点击列表中的「编辑」链接,会调用 edit 方法,该方法的实现代码如下
edit(link: LinkDto) {
this.resetForm();
this.router.navigate([], {
queryParams: {
edit: link.id,
},
queryParamsHandling: 'merge',
});
this.isEditing = true;
this.editingDto = { ...link };
}
遇到的问题是点击「编辑」后表单中的控件内容全为空,edit 方法的 link 参数有数据
angular 版本是 19
解决方法一:在 router.navigate 之后调用 FormGroup 的 reset 方法重置并设置表单控件的值
this.editLinkForm.reset({
categoryId: this.editingDto.categoryId,
title: this.editingDto.title,
url: this.editingDto.url,
});
解决方法二:在 router.navigate 之后重新创建 FormGroup
引入一个专门创建 FormGroup 的方法
private createFormGroup() {
return this.fb.group({
categoryId: [this.editingDto.categoryId, linkDtoValidators.categoryId],
title: [this.editingDto.title, linkDtoValidators.title],
url: [this.editingDto.url, linkDtoValidators.url],
});
}
构造函数与 router.navigate 之后都调用这个方法
this.editLinkForm = this.createFormGroup();
The updateOn Option in Angular Forms
– dudu 5个月前