在角度6中创建用于交叉字段验证的自定义指令(确认密码)

时间:2018-07-30 06:49:26

标签: angular typescript angular6 angular-directive

我创建了一个组件(set-pass),我想在该组件中执行密码并确认密码活动。我通过在共享文件夹中创建一个自定义指令(confirm-equal-validator.directive.ts)来进行尝试。

下面是我的组件文件

set-pass.component.html

    <form >
      <mat-form-field >
        <input matInput name="password" placeholder="New password" [type]="hide ? 'password' : 'text'" [formControl]="passFormControl" required>

        <mat-icon matSuffix (click)="hide = !hide">{{hide ? 'visibility' : 'visibility_off'}}</mat-icon>
        <mat-error *ngIf="passFormControl.hasError('required')">
            Please enter your newpassword
          </mat-error>
      </mat-form-field>

      <mat-form-field >
        <input matInput name="confirmPassword"  appConfirmEqualValidator="password"  placeholder="Confirm password" [type]="hide ? 'password' : 'text'" [formControl]="confirmFormControl" #confirmPasswordControl="ngModel" required>

        <mat-icon matSuffix (click)="hide = !hide">{{hide ? 'visibility' : 'visibility_off'}}</mat-icon>
        <mat-error *ngIf="confirmFormControl.hasError('required')">
          Confirm your password
          </mat-error>
          <mat-error *ngIf="confirmFormControl.hasError('notEqual')">
            Confirm your password
            </mat-error>
      </mat-form-field>
   </form>

set-pass.component.ts

    import {Component, OnInit } from '@angular/core';
    import {FormControl, FormGroupDirective, NgForm, Validators} from 
         '@angular/forms';
    import {ErrorStateMatcher} from '@angular/material/core';

     @Component({
       selector: 'ylb-set-pass',
       templateUrl: './set-pass.component.html',
       styleUrls: ['./set-pass.component.css']
       })
     export class SetPassComponent {

        passFormControl = new FormControl('', [
        Validators.required,
         ]);
           confirmFormControl = new FormControl('', [
          Validators.required,
        ]);
   }

confirm-equal-validator.directive.ts(位于共享文件夹中)

    import { Validator,AbstractControl,NG_VALIDATORS } from '@angular/forms';
    import { Directive,Input} from '@angular/core';



    @Directive({
       selector: '[appConfirmEqualValidator]',
       providers: [{
            provide: NG_VALIDATORS,
            useExisting: ConfirmEqualValidatorDirective ,
            multi:true
        }]
     })

   export class ConfirmEqualValidatorDirective implements Validator{
     @Input() appConfirmEqualValidator:string;
      validate(control: AbstractControl):{[key:string]:any} | null{
        const controlToCompare = 
    control.parent.get(this.appConfirmEqualValidator);
        if(controlToCompare && controlToCompare.value !== control.value){
           return{'notEqual':true};
         }
         return null;
       }
     }

我已经将这样的组件导入了app.module.ts中

    import { ConfirmEqualValidatorDirective } from './shared/confirm-equal-validator.directive';

我已经按照视频中给出的所有步骤操作

    https://www.youtube.com/watch?v=YhazkQd59Hk

最终在CMD中出现此错误

    ERROR in src/main.ts(5,29): error TS2307: Cannot find module './environments/environment'.

我只想通过材料组件来实现确认密码, 像这样

enter image description here

2 个答案:

答案 0 :(得分:1)

撇开您的错误,有一种更简便的方法来检查密码是否匹配。

鉴于您有两个像您一样的表单控件:

<input matInput name="password" placeholder="New password" [formControl]="passFormControl" required (blur)="checkPasswordControls()">
<input matInput name="password" placeholder="Confirm password" [formControl]="confirmFormControl" required (blur)="checkPasswordControls()">
checkPasswordControls() {
  if (this.passFormControl.value !== this.confirmFormControl.value) {
    this.passFormControl.setErrors({ notEqual: true });
    this.confirmFormControl.setErrors({ notEqual: true });
  } else {
    this.passFormControl.setErrors(this.passFormControl.errors ? { ...this.passFormControl.errors } : null);
    this.confirmFormControl.setErrors(this.confirmFormControl.errors ? { ...this.confirmFormControl.errors } : null);
  }
}

现在,每次您留下任何一个输入时,您的组件都将检查两个表格的值是否匹配:如果不匹配,它将在两个输入上设置一个错误。

这使您可以删除指令(并且由于只使用一次该指令,因此不需要指令),因此阅读时间较短,更清晰,更易于理解。

答案 1 :(得分:0)

无法找到模块'./environments/environment',请检查当前目录中是否有任何名为环境的文件夹,即.. src> app> environment> environment.ts,environment.prod.ts 问题在于您的主模块依赖于环境文件夹,并且不存在,主要是如果您使用的是vscode或其他智能编辑器,未解决的目录错误将在编辑器本身中获取。