Angular2 反应形式确认值的相等性 [英] Angular2 reactive form confirm equality of values

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

问题描述

我正在尝试创建一个 Angular2 Reactive 表单,我必须在其中确认用户输入的电子邮件地址.这是 plunker

的链接

import { Component, OnInit } from '@angular/core';从@angular/forms"导入 { FormControl, FormGroup, Validators };从'./signup.interface'导入{用户};@成分({选择器:'注册表单',模板:`<form novalidate (ngSubmit)="onSubmit(user)" [formGroup]="user"><标签><span>全名</span><input type="text" placeholder="您的全名" formControlName="name"><div class="error" *ngIf="user.get('name').touched && user.get('name').hasError('required')">姓名为必填项

<div class="error" *ngIf="user.get('name').touched && user.get('name').hasError('minlength')">最少 2 个字符

<div formGroupName="帐户"><标签><span>电子邮件地址</span><input type="email" placeholder="您的电子邮件地址" formControlName="email">

电子邮件是必需的

<标签><span>确认地址</span><input type="email" placeholder="确认您的电子邮件地址" formControlName="confirm">

需要确认电子邮件

<button type="submit" [disabled]="user.invalid">注册</button></表单>`})导出类 SignupFormComponent 实现 OnInit {用户:FormGroup;构造函数(){}ngOnInit() {this.user = new FormGroup({名称:new FormControl('', [Validators.required, Validators.minLength(2)]),帐户:新表单组({电子邮件:new FormControl('', Validators.required),确认:new FormControl('', Validators.required)})});}onSubmit({ value, valid }: { value: User, valid: boolean }) {控制台日志(值,有效);}}

当这两个电子邮件字段不匹配时,我想显示错误.

如何使用 angular2 中的反应式形式为这种行为创建这样的验证?

我看过一篇文章,它使用模板驱动的方法来做到这一点此处,但我无法弄清楚如何使用反应式表单方法来做到这一点.

解决方案

我已经使用反应式表单完成了密码匹配.您可以将其更改为电子邮件.只需更改电子邮件验证器代替密码.两者都是字符串,其他一切都相同,并在电子邮件中输入密码匹配错误.它会起作用

app.module.ts

将这些添加到您的 app.module.ts 文件中以使用响应式表单

import { NgModule } from '@angular/core';从'@angular/platform-b​​rowser' 导入 { BrowserModule };从@angular/forms"导入 { FormsModule, ReactiveFormsModule };从 './app.component' 导入 { AppComponent };@NgModule({进口:[浏览器模块,表单模块,反应形式模块,],声明: [应用组件]提供者:[],引导程序:[应用组件]})导出类 AppModule {}

app.component.ts

import { Component,OnInit } from '@angular/core';从'./add.component.html'导入模板;导入 { FormGroup,FormBuilder,Validators } from '@angular/forms';从'./validators'导入{匹配密码};@成分({选择器:'应用',模板})导出类 AppComponent 实现 OnInit {添加表单:表单组;构造函数(私有表单构建器:FormBuilder){}ngOnInit() {this.addForm = this.formBuilder.group({用户名:['', Validators.required],电子邮件:['',Validators.required],角色: ['', Validators.required],密码:['', Validators.required],密码 2: ['', Validators.required] },{ 验证器:matchingPasswords('password', 'password2') <-- 用 email_1 和 email_2 替换 args})};添加用户() {如果(this.addForm.valid){var adduser = {用户名:this.addForm.controls['username'].value,电子邮件:this.addForm.controls['email'].value,密码:this.addForm.controls['password'].value,轮廓: {角色:this.addForm.controls['role'].value,名称:this.addForm.controls['username'].value,电子邮件:this.addForm.controls['email'].value}};console.log(adduser);//adduser var 包含我们所有的表单值.将其存放在您想要的地方this.addForm.reset();//这会将我们的表单值重置为空}}}

app.component.html

<form [formGroup]="addForm"><input type="text" placeholder="输入用户名" formControlName="用户名"/><input type="text" placeholder="输入电子邮件地址" formControlName="email"/><input type="password" placeholder="输入密码" 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')">密码不匹配

<select name="Role" formControlName="role"><option value="admin" >Admin</option><option value="Accounts">Accounts</option><option value="guest">Guest</option></选择><br/><br/><button type="submit" (click)="addUser()"><span><i class="fa fa-user-plus" aria-hidden="true"></i></span>添加用户</button></表单>

validators.ts

export function matchingPasswords(passwordKey: string, confirmPasswordKey: string) {返回(组:ControlGroup):{[键:字符串]:任何} =>{让密码 = group.controls[passwordKey];让confirmPassword = group.controls[confirmPasswordKey];如果(密码.值!== 确认密码.值){返回 {mismatchedPasswords: true};}}}

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.

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

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

<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

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 反应形式确认值的相等性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
前端开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆