After creating a component called set-pass, I aimed to handle the password and confirm password functionalities within this component. To achieve this, I experimented by crafting a custom directive (confirm-equal-validator.directive.ts) located inside the shared folder.
Here's an overview of my component files:
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 new password
</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(present inside shared folder)
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;
}
}
I have imported this component in app.module.ts like this
import { ConfirmEqualValidatorDirective } from './shared/confirm-equal-validator.directive';
I took all necessary steps as outlined in this video tutorial:
https://www.youtube.com/watch?v=YhazkQd59Hk
An error was reported in CMD as follows:
ERROR in src/main.ts(5,29): error TS2307: Cannot find module './environments/environment'.
My goal is to implement the confirm password feature using Material components exclusively, similar to this example: