javascript - 以 react 形式设置嵌套表单组/控件值

标签 javascript angular typescript

我的应用程序中有一个Reactive Form,结构如下:

this.bioForm = this._fb.group({
  firstName: [this.user.firstName, [Validators.required]],

  experience: this._fb.group({
    field0: ['', [Validators.required, Validators.maxLength(500)]],
    field1: ['', [Validators.required, Validators.maxLength(500)]],
    field2: ['', [Validators.required, Validators.maxLength(500)]],
    field3: ['', [Validators.required, Validators.maxLength(500)]],
    field4: ['', [Validators.maxLength(500)]],
    field5: ['', [Validators.maxLength(500)]]
  }),

  skills: this._fb.array([], Validators.required),
});

在我的浏览器本地存储中,我有以下内容:

enter image description here

我尝试过的:

 // Get Value from LOCAL STORAGE
 let localStorage_experience = JSON.parse(localStorage.getItem("experience")) || "";

 // Set nested form controls value
 this.bioForm.setValue({experience:{field0: localStorage_experience.field0 || ""}});

我正在尝试从我的本地存储中检索值并将它们设置为我的嵌套表单控件值。

最佳答案

您可以使用 setControl 替换现有的 formcontrol/formgroup/formarray:

this.bioForm.setControl('experience', this._fb.group(localStorage_experience));

StackBlitz

或者你可以使用patchValue:

this.bioForm.patchValue({experience: localStorage_experience}); 

如果您想使用 setValue,您需要在嵌套的表单组上应用它,因为 setValue 期望设置所有 值。

this.bioForm.controls.experience.setValue(localStorage_experience);

关于javascript - 以 react 形式设置嵌套表单组/控件值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48866786/

相关文章:

excel - 从 Excel 任务 Pane 内的 Angular 应用程序读取 Office 加载项 list 文件的设置

javascript - 编译 typescript 并保持正确的目录结构

javascript - 创建通用自定义组件 React

javascript - 如何将外部 util 类包含并内联到主 TypeScript 应用程序中?

javascript - 如何根据所使用的 URL 使用 javascript 更改页面内容?

javascript - src/app/app-routing.module.ts(10,11) : error TS1005: ',' expected 中的错误

javascript - 从顶级组件中的延迟加载路由获取自定义路由数据

javascript - Buefy 工具提示中的新行

javascript - TypeError: Undefined 不是一个函数。 iOS Safari 评估功能。 CoffeeScript

javascript - 在受尊敬的父级上切换下拉菜单的 ngClass