加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-17 18:10:08 所属栏目:安全 来源:网络整理
导读:我试图在Angular 2中实现一个模型驱动的表单.我的数据模型的结构如下: archive (FormGroup) name (FormControl) description (FormControl) connection (FormGroup) url (FormControl) authentication (FormGroup) username (FormControl) password (FormCo
我试图在Angular 2中实现一个模型驱动的表单.我的数据模型的结构如下:

archive (FormGroup)
    name (FormControl)
    description (FormControl)
    connection (FormGroup)
        url (FormControl)
        authentication (FormGroup)
            username (FormControl)
            password (FormControl)

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

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

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

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

解决方法

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

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))
});

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
      };
    }
}

对于输出,如果只填写名称,您仍将拥有:

{
  "name": null,"description": null,"connection": {
    "url": null,"authentification": {
      "username": null,"password": null
    }
  }
}

所以你必须条件创建一个新对象:

{
  "name": null,"connection": null
}

Check this plunker to experiment this solution

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读