Angular2反应形式确认了价值的平等

Angular2反应形式确认了价值的平等

本文介绍了Angular2反应形式确认了价值的平等的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个Angular2 Reactive表单,我必须确认用户输入的电子邮件地址。以下是的链接

I am trying to create an Angular2 Reactive form where I have to confirm the email address entered by the user. Here is a link to the plunker

import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { User } from './signup.interface';

@Component({
selector: 'signup-form',
template: `
    <form novalidate (ngSubmit)="onSubmit(user)" [formGroup]="user">
    <label>
        <span>Full name</span>
        <input type="text" placeholder="Your full name" formControlName="name">
    </label>
    <div class="error" *ngIf="user.get('name').touched && user.get('name').hasError('required')">
        Name is required
    </div>
    <div class="error" *ngIf="user.get('name').touched && user.get('name').hasError('minlength')">
        Minimum of 2 characters
    </div>
    <div formGroupName="account">
        <label>
        <span>Email address</span>
        <input type="email" placeholder="Your email address" formControlName="email">
        </label>
        <div
        class="error"
        *ngIf="user.get('account').get('email').hasError('required') && user.get('account').get('email').touched">
        Email is required
        </div>
        <label>
        <span>Confirm address</span>
        <input type="email" placeholder="Confirm your email address" formControlName="confirm">
        </label>
        <div
        class="error"
        *ngIf="user.get('account').get('confirm').hasError('required') && user.get('account').get('confirm').touched">
        Confirming email is required
        </div>
    </div>
    <button type="submit" [disabled]="user.invalid">Sign up</button>
    </form>
`
})
export class SignupFormComponent implements OnInit {
  user: FormGroup;
  constructor() {}
  ngOnInit() {
    this.user = new FormGroup({
    name: new FormControl('', [Validators.required, Validators.minLength(2)]),
      account: new FormGroup({
        email: new FormControl('', Validators.required),
        confirm: new FormControl('', Validators.required)
      })
    });
  }
  onSubmit({ value, valid }: { value: User, valid: boolean }) {
    console.log(value, valid);
  }
}

我想在这两个电子邮件字段不匹配时显示错误。

I want to show an error when these 2 email fields mismatch.

如何为此创建此类验证是使用angular2中的反应形式的行为吗?

How can I create such a validation for this behaviour using reactive forms in angular2 ?

我看过一个使用模板驱动方法执行此操作的帖子,但我无法弄清楚如何使用它反应形式方法。

I have seen a post which does this using template driven approach here, but I was not able to figure out how I could do it using reactive form approach.

推荐答案

我已经使用被动形式进行了密码匹配。你可以改变电子邮件。只需更改电子邮件验证器代替密码即可。两个都是字符串其他一切都相同,并在电子邮件中输入密码匹配错误。它将工作

I have done password matching using reactive forms. you can change it for email. Just change validator for emails in place of password. both are string everything else is same and put passwordmatch error in email.It will work

将这些添加到app.module.ts文件中以使用被动表格

Add these into your app.module.ts file to use reactive forms

import { NgModule } from '@angular/core';
    import { BrowserModule } from '@angular/platform-browser';
    import { FormsModule, ReactiveFormsModule } from '@angular/forms';
    import { AppComponent } from './app.component';
    @NgModule({
      imports: [
        BrowserModule,
        FormsModule,
        ReactiveFormsModule,
     ],
    declarations: [
    AppComponent
     ]
  providers: [],
  bootstrap: [
    AppComponent
   ]
  })
export class AppModule {}



app.component.ts



app.component.ts

import { Component,OnInit } from '@angular/core';
import template from './add.component.html';
import { FormGroup,FormBuilder,Validators } from '@angular/forms';
import { matchingPasswords } from './validators';
@Component({
    selector: 'app',
    template
})
export class AppComponent implements OnInit {
    addForm: FormGroup;
    constructor(private formBuilder: FormBuilder) {
    }
    ngOnInit() {

    this.addForm = this.formBuilder.group({
            username: ['', Validators.required],
            email: ['', Validators.required],
            role: ['', Validators.required],
            password: ['', Validators.required],
            password2: ['', Validators.required] },
          { validator: matchingPasswords('password', 'password2') <-- replace args with email_1 and email_2
        })
    };

addUser() {
        if (this.addForm.valid) {
            var adduser = {
                username: this.addForm.controls['username'].value,
                email: this.addForm.controls['email'].value,
                password: this.addForm.controls['password'].value,
                profile: {
                    role: this.addForm.controls['role'].value,
                    name: this.addForm.controls['username'].value,
                    email: this.addForm.controls['email'].value
                }
            };
          console.log(adduser);// adduser var contains all our form values. store it where you want
            this.addForm.reset();// this will reset our form values to null
        }
    }
}



app.component.html



app.component.html

<div>
  <form [formGroup]="addForm">
   <input type="text" placeholder="Enter username" formControlName="username" />
   <input type="text" placeholder="Enter Email Address" formControlName="email"/>
   <input type="password" placeholder="Enter Password" formControlName="password" />
   <input type="password" placeholder="Confirm Password" name="password2" formControlName="password2"/>
   <div class='error' *ngIf="addForm.controls.password2.touched">
    <div class="alert-danger errormessageadduser" *ngIf="addForm.hasError('mismatchedPasswords')">                                  Passwords do not match
  </div>
</div>
<select name="Role" formControlName="role">
    <option value="admin" >Admin</option>
    <option value="Accounts">Accounts</option>
    <option value="guest">Guest</option>
</select>
<br/>
<br/>
<button type="submit" (click)="addUser()"><span><i class="fa fa-user-plus" aria-hidden="true"></i></span> Add User </button>
</form>
</div>



validators.ts



validators.ts

export function matchingPasswords(passwordKey: string, confirmPasswordKey: string) {
    return (group: ControlGroup): {
        [key: string]: any
    } => {
        let password = group.controls[passwordKey];
        let confirmPassword = group.controls[confirmPasswordKey];

        if (password.value !== confirmPassword.value) {
            return {
                mismatchedPasswords: true
            };
        }
    }
}

这篇关于Angular2反应形式确认了价值的平等的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 02:51