gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 09:26:50 24 4
gpt4 key购买 nike

我的应用程序中有一个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/

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