【问题标题】:Password Confirm Reactive Forms Angular 4 [duplicate]密码确认反应形式Angular 4 [重复]
【发布时间】:2018-03-15 08:00:34
【问题描述】:

我的密码有问题,并在我的 Angular 应用程序中确认密码。我正在使用响应式表单,错误提示“提供的参数与调用目标上的任何签名都不匹配”

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>

【问题讨论】:

  • 您还没有关闭 ngOnInit 的括号

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


【解决方案1】:

将你的passwordConfirming外部组件类声明为函数,然后调用它,例如:

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>

【讨论】:

  • 弹出模式被破坏
  • 什么是弹出模式?我认为这将是另一个错误
  • 弹出模式被破坏,因为我实现了你的代码
  • 我刚刚粘贴了我没有收到任何语法错误的代码
  • TypeError:无法在 Array.map () 的 forms.es5.js:506 处的 passwordConfirming (user-management.component.ts:8) 处读取 null 的属性“值”跨度>
猜你喜欢
  • 2017-12-15
  • 2017-09-15
  • 2019-05-12
  • 1970-01-01
  • 1970-01-01
  • 2019-06-17
  • 2019-12-28
  • 2019-01-07
  • 2018-06-16
相关资源
最近更新 更多