密码确认反应表格Angular 4

时间:2017-10-04 02:38:48

标签: angular angular-reactive-forms angular-forms

我的密码问题和在我的角应用中确认密码有问题。我正在使用被动表单,错误显示“提供的参数与呼叫目标上的任何签名都不匹配”

ngOnInit() {
      this.form = this.formBuilder.group({
        name: [null, [Validators.required, Validators.minLength(3)]],
        email: [null, [Validators.required, Validators.email]],
        password: [null, Validators.required],
        confirm_password: [null, Validators.required],
      }, {validator: this.passwordConfirming('password', 'confirm_password')});

}
  passwordConfirming(c: AbstractControl): { invalid: boolean } {
    if (c.get('password').value !== c.get('confirm_password').value) {
        return {invalid: true};
    }
  }
  

HTML

<div class="form-inline">       
    <label class="col-md-4">Password</label>
    <input class="col-md-8" type="password" class="form-control" id="password" formControlName="password">
    <span class="text-muted" *ngIf="!form.controls['password'].valid && form.controls['password']?.touched"> Password is required</span>
 </div>
 <div class="form-inline">       
    <label class="col-md-4">Confirm Password</label>
    <input class="col-md-8" type="password" class="form-control" id="confirm_password" formControlName="confirm_password">

 </div>

1 个答案:

答案 0 :(得分:7)

声明你的密码在组件类外部确认为函数,然后调用它,例如:

import { AbstractControl, FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
import { Component, OnInit, ViewChild } from '@angular/core';

function passwordConfirming(c: AbstractControl): any {
    if(!c.parent || !c) return;
    const pwd = c.parent.get('password');
    const cpwd = c.parent.get('confirm_password');

    if(!pwd || !cpwd) return ;
    if (pwd.value !== cpwd.value) {
        return { invalid: true };
    }
}

@Component({
    templateUrl: './my.component.html',
    styleUrls: ['./my.component.scss']
})
export class MyComponent implements OnInit {
    form: FormGroup;
    get cpwd() {
        return this.form.get('confirm_password');
    }
    constructor(private formBuilder: FormBuilder) {}

    ngOnInit() {
        this.form = this.formBuilder.group({
            name: [null, [Validators.required, Validators.minLength(3)]],
            email: [null, [Validators.required, Validators.email]],
            password: [null, Validators.required],
            confirm_password: [null, [Validators.required, passwordConfirming]]
        });
    }    
}

HTML代码:

<span *ngIf="cpwd.hasError('invalid')"> Invalid Password </span>