具有反应形式的 Angular patchValue json 数据

发布于 2025-01-13 08:02:49 字数 1105 浏览 2 评论 0 原文

我正在编辑页面,并尝试使用从 API 获得的数据设置表单默认值。

我的问题是我的数组中有两个项目,但它创建了另一个空的 formArray;

我做错了什么?

这是我的 stackblitz

  this.filterForm = this.fb.group({
      categories: this.fb.array([this.initCat()]),
    });

    const control = <FormArray>this.filterForm.get('categories');
    console.log(control);
    this.chosenCarPartCategories.carPartCategories.forEach((x) => {
      control.push(
        this.patchValues(x.name, x.carPartSubCategoryId, x.quantity, x.comment)
      );
    });

  patchValues(name, carPartSubCategoryId, quantity, comment) {
    return this.fb.group({
      carPartCategory: [name],
      carPartSubCategory: [carPartSubCategoryId],
      quantity: [quantity],
      comment: [comment],
    });
  }

  initCat() {
    return this.fb.group({
      carPartCategory: ['', Validators.required],
      carPartSubCategory: ['', Validators.required],
      quantity: ['', Validators.required],
      comment: [''],
    });
  }

I am doing edit page and I am trying to set my forms default value with data I got from API.

My issue is that I have two items in my array but it creates another empty formArray;

What am I doing wrong?

here is my stackblitz

  this.filterForm = this.fb.group({
      categories: this.fb.array([this.initCat()]),
    });

    const control = <FormArray>this.filterForm.get('categories');
    console.log(control);
    this.chosenCarPartCategories.carPartCategories.forEach((x) => {
      control.push(
        this.patchValues(x.name, x.carPartSubCategoryId, x.quantity, x.comment)
      );
    });

  patchValues(name, carPartSubCategoryId, quantity, comment) {
    return this.fb.group({
      carPartCategory: [name],
      carPartSubCategory: [carPartSubCategoryId],
      quantity: [quantity],
      comment: [comment],
    });
  }

  initCat() {
    return this.fb.group({
      carPartCategory: ['', Validators.required],
      carPartSubCategory: ['', Validators.required],
      quantity: ['', Validators.required],
      comment: [''],
    });
  }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

我也只是我 2025-01-20 08:02:49

很难理解你想在这里做什么,仅供参考。但您描述的问题来自 this.initCat()

    this.filterForm = this.fb.group({
      categories: this.fb.array([this.initCat()]),
    });

将其删除以删除空的额外表格。

    this.filterForm = this.fb.group({
      categories: this.fb.array([]),
    });

Very difficult to understand what you're trying to do here, fyi. But your described problem comes from this.initCat().

    this.filterForm = this.fb.group({
      categories: this.fb.array([this.initCat()]),
    });

Remove it to remove the empty extra form.

    this.filterForm = this.fb.group({
      categories: this.fb.array([]),
    });
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文