如何创建嵌套的表单组,基于模型的反应形式

时间:2019-02-09 06:45:09

标签: angular angular-reactive-forms

我有一个User形式的反应形式,并且我使用了RxFormBuilder包中的@rxweb,我有一个包含UserInfo对象的用户模型类,我该如何用作嵌套的formgroup吗?

model.ts:

import {prop,propArray } from "@rxweb/reactive-form-validators"
export class UserInfo{
   @prop()
   cityId: number 

   @prop()
   countryId: number;
}

export class User{
 @prop()
 userId: string;

 @prop()
 password: string;

@prop()
securityQuestion: string;

 @prop()
 userInfo : UserInfo;

}

component.ts:

export class UserInfoComponent implements OnInit {

    userInfoFormGroup: FormGroup

    constructor(
        private formBuilder: RxFormBuilder
    ) { }

    ngOnInit() {
        this.userInfoFormGroup = this.formBuilder.formGroup(User);
    }
}

我想在用户模型中将UserInfo对象用作嵌套的formgroup。如何创建嵌套的formgroup

这是一个stackblitz链接: https://stackblitz.com/edit/rxweb-nested-formgroup-using-model

1 个答案:

答案 0 :(得分:1)

根据@rxweb/reactive-form-validators中的an example,您应该使用userInfo装饰器来装饰@propObject属性:

import { propObject} from "@rxweb/reactive-form-validators";

export class User {
  ...

  @propObject(UserInfo)
  userInfo: UserInfo;
}

还要像这样初始化FormGroup

ngOnInit() {
    let user = new User();
    user.userInfo = new UserInfo();
    this.userInfoFormGroup = this.formBuilder.formGroup(user);
}

Forked Stackblitz