zoukankan      html  css  js  c++  java
  • [Angular2 Form] Nested formGroup, and usage of formGroupName

    We can nest formGorup:

        this.reactiveForm = fb.group({
          username: [
            '',
            [
              Validators.required,
              Validators.minLength(3)
            ]
          ],
          pwds: fb.group({
            pwd: '',
            rpwd: ''
          }, {validator: passwordValidator})
        });

    We make password as an own group. So in html, we need to use formGroupName istead of formControlName.

    <form [formGroup]="reactiveForm" novalidate autocomplete="off">
      <div class="form-field">
        <label>Username:</label>
        <input formControlName="username">
        <div class="field-error-message" *ngIf="reactiveForm.controls.title.errors?.required">
          Username is required
        </div>
      </div>
    
      <div formGroupName="pwds">
        <div class="form-field">
          <label>pwd</label>
          <input formControlName="pwd">
        </div>
        <div class="form-field">
          <label>rpwd</label>
          <input formControlName="rpwd">
        </div>
      </div>
    </form>

    And how we check the value or errors?:

    <pre>
      {{reactiveForm.get('pwds')?.value | json}}
      {{reactiveForm.get('pwds')?.errors | json}}
    </pre>

    And we also passwordValidator haven't cover yet, it is just a fucntion:

    function passwordValidator(c: AbstractControl){
      return c.get('pwd').value === c.get('rpwd').value ?
        null : // valid
        { //invalid
          nomatch: true
        }
    }

    And notice that we put this validator inside the nested group, so we can get nice error effect:

  • 相关阅读:
    职业规划书
    阿里云mysql安装配置(CentOS 7.3 64)
    在mvc中弹出提示框
    俺的博客开通啦
    sql中计算列小解
    ext的grid 获取页面内容方式
    2条路 代码生成 or 配置 2.1
    ext做列表页面关于查询多行的办法
    .net下开发windows服务的经验
    微软.net下 charting 要注意的事情
  • 原文地址:https://www.cnblogs.com/Answer1215/p/6018120.html
Copyright © 2011-2022 走看看