typescript Angular 窗体组数组

c2e8gylq  于 2023-02-05  发布在  TypeScript
关注(0)|答案(2)|浏览(129)

我有一个问题,设置数据的形式数组。场景是当填写用户详细信息,一些用户有多个地址。
这是用户.ts

export interface User {
  id?: number;
  name: string;
  age: number;
  address: MyAddress;
}

MyAddress.ts

export interface MyAddress {
  id?: number;
  line1: string;
  line2: string;
  postalCode: string;
  city: string;
}

在组件.ts文件中

myForm = this.formBuilder.group({
    name: ['', Validators.required],
    age: ['', Validators.required]
});

myFormAddress = this.formBuilder.group({
    address: this.formBuilder.array([]),
});

setDetail(): User {
    let myObj = new User();
    myObj.name = this.myForm.controls.name.getRawValue();
    myObj.age = this.myForm.controls.description.getRawValue();
    
    myObj.address = {
      //need to set form array dta here
    }
    
    return myObj;
  }
xytpbqjk

xytpbqjk1#

您不需要两个表单组:

myForm = this.formBuilder.group({
    name: ['', Validators.required],
    age: ['', Validators.required],
    address: this.formBuilder.array([]),
});
ql3eal8s

ql3eal8s2#

您的用户界面应反映具有多个地址的可能性:

export interface User {
  id?: number;
  name: string;
  age: number;
  address: MyAddress[];
}

和地址应该是myForm的一部分:

myForm = this.formBuilder.group({
  name: ['', Validators.required],
  age: ['', Validators.required],
  address: this.formBuilder.array([]),
});

然后,您应该能够像处理常规表单控件那样获取数组:

myObj.address = this.myForm.controls.address.getRawValue();

另一种选择是从表单值中获取整个对象:

myObj = this.myForm.value as User;

相关问题