我正在编辑页面,我试图用从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: [''],
    });
  }

推荐答案

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

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

移除它以移除空的额外表单.

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

Typescript相关问答推荐

类型脚本:类型是通用的,只能索引以供阅读.(2862)"

相同端点具有不同响应时的RTKQuery类型定义

根据另一个成员推断类成员的类型

动态判断TypScript对象是否具有不带自定义类型保护的键

异步动态生成Playwright测试,显示未找到测试

是否可以从函数类型中创建简化的类型,go 掉参数中任何看起来像回调的内容,而保留其余的内容?

寻址对象中路径的泛型类型

通过泛型函数本身推断受约束的泛型参数的类型脚本问题

常量类型参数回退类型

是否有可能避免此泛型函数体中的类型断言?

与toast.error一起react 中的Async TUNK错误消息

如何编辑切片器以使用CRUD调用函数?

如何连接属性名称和值?

如何从上传文件中删除预览文件图标?

如何在Next.js和Tailwind.css中更改悬停时的字体 colored颜色

为什么TS条件返回要求不明确的强制转换而不是精确的强制转换?

使用嵌套属性和动态执行时,Typescript 给出交集而不是并集

TS 条件类型无法识别条件参数

基于泛型的柯里化函数的条件参数

如何为对象创建类型,其中键是只读且动态的,但值是固定类型?