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:

  • 相关阅读:
    Server responded "Algorithm negotiation failed" SSH Secure链接服务器错误
    简单实现elementui的el-container布满全屏
    安装apue.h
    编译原理
    点亮一盏灯
    什么是Complement(补码)?(转)
    轻松学C语言
    求二进制表示
    gst-launch-1.0 (1)
    使用docker-compose 大杀器来部署服务 上 (转)
  • 原文地址:https://www.cnblogs.com/Answer1215/p/6018120.html
Copyright © 2011-2022 走看看