如何在单个组件中验证多个表单?(响应式表单验证)

时间:2019-01-11 11:07:12

标签: angular

<div class="modal-body">
<ul class="nav nav-pills" role="tablist">
    <li class="nav-item"><a class="nav-link active" data-toggle="pill" href="#EmployerLogin">Employer</a></li>
    <li class="nav-item"><a class="nav-link" data-toggle="pill" href="#seekerLogin">Candidate</a></li>
</ul>
<div class="tab-content">
    <div id="EmployerLogin" class="tab-pane  active">
        <form class="form-horizontal" [formGroup]="registerForm" (ngSubmit)="employerLogin()">
            <input type="email" [(ngModel)]="emplogin.employer_email" formControlName="elogin" name="empname" class="form-control"
                [ngClass]="{ 'is-invalid': submitted && f.elogin.errors }" placeholder="Email">
            <div *ngIf="submitted && f.elogin.errors" class="invalid-feedback">
                <div *ngIf="f.elogin.errors.required"> Email is required</div>
            </div>
            <button class="btn btn-default">Login</button>
        </form>
    </div>
    <div id="seekerLogin" class="tab-pane fade">
        <form class="form-horizontal" [formGroup]="registerForm" (ngSubmit)="seekerLogin()">
            <input type="text" [(ngModel)]="seekerlogin.seeker_email" formControlName="empEmail" name="empname"
                class="form-control" [ngClass]="{ 'is-invalid': submitted && f.empEmail.errors }" placeholder="Email">
            <div *ngIf="submitted && f.empEmail.errors" class="invalid-feedback">
                <div *ngIf="f.empEmail.errors.required"> Email is required</div>
            </div>
            <button class="btn btn-default">Login</button>
        </form>
    </div>
</div>

login.ts

 import { Component, OnInit } from '@angular/core';
    import { FormBuilder, FormGroup, Validators } from '@angular/forms';
    @Component({
        selector: 'my-Header',
        templateUrl: './header.component.html',
    })
    export class HeaderComponent implements OnInit {
        constructor(private formBuilder: FormBuilder) { }
        registerForm: FormGroup;
        ngOnInit() {
            this.registerForm = this.formBuilder.group({
                elogin: ['', Validators.required]
            });
        }
        submitted: Boolean = false;
        // Employer  Login Method
       get f() { return this.registerForm.controls; }

        employerLogin() {
            this.submitted = true;
            if (this.registerForm.invalid) {
                return;
            }
        }
        // Seeker  Login Method
        seekerLogin() {
            this.submitted = true;
            if (this.registerForm.invalid) {
                return;
            }
        }
    }

如何验证两种形式,当我尝试验证其中一种形式时,对于双方都显示出错误。是否还有其他方法可以使用Angular 6验证单个组件中的多种形式。请注意,我对Angular还是很陌生6和打字稿,所以我可能缺少明显的东西。 :)

2 个答案:

答案 0 :(得分:1)

由于您使用的是submitted布尔属性来检查两个表单,并且每个表单都有一个应用了Validators.required的字段,因此仅使用一个{{ 1}}。

您将必须完全创建两个不同的FormGroup,或者必须在同一FormGroup FormGroup中创建两个不同的registerForm

我将在此答案中展示后一种方法:

这是您的组件:

FormGroup

然后在您的组件模板中,绑定到以下FormGroups:

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  constructor(private formBuilder: FormBuilder) { }
  registerForm: FormGroup;
  ngOnInit() {
    this.registerForm = this.formBuilder.group({
      employerGroup: this.formBuilder.group({
        elogin: ['', Validators.required]
      }),
      candidateGroup: this.formBuilder.group({
        empEmail: ['', Validators.required]
      })
    });
  }
  employerSubmitted: boolean = false;
  candidateSubmitted: boolean = false;
  // Employer  Login Method
  get fe() { return (<FormGroup>this.registerForm.get('employerGroup')).controls; }

  get fc() { return (<FormGroup>this.registerForm.get('candidateGroup')).controls; }

  get employerGroup() {
    return this.registerForm.get('employerGroup');
  }

  get candidateGroup() {
    return this.registerForm.get('candidateGroup');
  }

  employerLogin() {
    this.employerSubmitted = true;
    if (this.registerForm.invalid) {
      return;
    }
  }
  // Seeker  Login Method
  seekerLogin() {
    this.candidateSubmitted = true;
    if (this.registerForm.invalid) {
      return;
    }
  }

}

  

这是您推荐的Working Sample StackBlitz

答案 1 :(得分:0)

您可以创建这样的表单结构:

"N"

在某些服务中创建此表单。现在,在组件中使用某种服务方法获取表单对象:

"N"

在组件中,您可以执行以下操作:

MasterForm = this.formbuilder.group({
grp1 = new FormGroup({
   formControl1,
   formControl2
}),
grp2 = new FormGroup({
   formControl3,
   formControl2
})
}, { validator: matchEmailsDomain(formControl1,formControl3)});

并且在html中将此myUserForm用作[formGroup] =“ myUserForm”;

在您的验证器中

getFormObject(){
   return this.MasterForm;
}