在Angular 2中创建可选的嵌套表单组

Tim*_*ean 6 reactive-forms angular

我试图在Angular 2中实现一个模型驱动的表单.我的数据模型的结构如下:

archive (FormGroup)
    name (FormControl)
    description (FormControl)
    connection (FormGroup)
        url (FormControl)
        authentication (FormGroup)
            username (FormControl)
            password (FormControl)
Run Code Online (Sandbox Code Playgroud)

在此数据模型中,顶级名称是必需的,但描述字段是可选的.我可以应用必需的验证器来命名,并省略描述中的验证器.

对于连接,我希望它是可选的,但如果存在连接,则其URL成为必需.类似地,对于连接的身份验证模型:它是可选的,但如果存在,则需要用户名和密码.

我试图了解如何设置验证器来强制执行这些规则.我试过从连接表单组中省略任何验证器,但这似乎要求我建立连接.我已经看过在线教程,解释了如何在嵌套表单组上实现自定义验证,但没有描述如何使整个嵌套表单组可选.

有没有一种直接的方法来使用Angular 2 FormGroup实现此模型?

ber*_*ndg 3

我有类似的需求,这是解决它的方法:

this.form = new FormGroup({
    'name': new FormControl(null, Validators.required),
    'description': new FormControl(null),
    'connection': new FormGroup({
        'url': new FormControl(null),
        'authentification': new FormGroup({
            'username': new FormControl(null, Validators.minLength(5)),
            'password': new FormControl(null),
        }, this.authentificationValidator.bind(this)),
    }, this.connectionValidator.bind(this))
});
Run Code Online (Sandbox Code Playgroud)

2 个验证器功能:

authentificationValidator(g: FormGroup): any {
    const username = g.get('username').value;
    const password = g.get('password').value;

    if( (username && !password) || (!username && password) ) {
        return {
            authentification: true
        };
    }
}

connectionValidator(g: FormGroup): any {
    const url = g.get('url').value;

    const authentification = g.get('authentification');
    const username = authentification.get('username').value;
    const password = authentification.get('password').value;

    if( (username || password) && !url ) {
      return {
          connection: true
      };
    }
}
Run Code Online (Sandbox Code Playgroud)

对于输出,如果只填写名称,您仍然会得到:

{
  "name": null,
  "description": null,
  "connection": {
    "url": null,
    "authentification": {
      "username": null,
      "password": null
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

因此,您必须有条件地创建一个新对象才能具有:

{
  "name": null,
  "description": null,
  "connection": null
}
Run Code Online (Sandbox Code Playgroud)

检查这个 plunker 来试验这个解决方案