Я студент, в настоящее время работающий над Angular 6 , и в настоящее время я сталкиваюсь с проблемой, которую не могу решить.
Цель моего кода «простая», это сделать подтверждение пароля для регистрационной формы .
Моя форма работает нормально, все входные данныепредставлены в .ts
.
Однако мой пользовательский валидатор, который подтверждает пароль, не работает.
Мой сервис должен вернуть ноль моему валидатору, но этого не происходит. Пароливсе те же, но кнопка сброса недействительна, и ввод «verify_password» также остается недействительным!
После многих попыток я не могу найти источник моей ошибки или что делать, чтобы исправить ее.
Может ли кто-нибудь помочь мне понять мои ошибки?
Заранее благодарю , вот код:
Мой HTML:
<div class="inscriptionContainer">
<section class='inscritFormContent'>
<form [formGroup]="loginForm" (ngSubmit)="onSubmit(loginForm.value)" >
<mat-form-field>
<input
type="text"
matInput
placeholder="user"
[formControl]="loginForm.controls.user" >
<mat-error *ngIf="loginForm.controls.user.invalid">{{getErrorMessage('user')}}</mat-error>
</mat-form-field>
<mat-form-field>
<input
type="text"
matInput
placeholder="email"
[formControl]="loginForm.controls.email">
<mat-error *ngIf="loginForm.controls.email.invalid">{{getErrorMessage('email')}}</mat-error>
</mat-form-field>
<mat-form-field>
<input
type="password"
matInput
placeholder="password"
[formControl]="loginForm.controls.password">
<mat-error *ngIf="loginForm.controls.password.invalid">{{getErrorMessage('password')}}</mat-error>
</mat-form-field>
<mat-form-field>
<input
type="password"
matInput
placeholder="confirm_password"
[formControl]="loginForm.controls.confirm_password">
<mat-error *ngIf="loginForm.controls.confirm_password.invalid">{{getErrorMessage('confirm_password')}}</mat-error>
</mat-form-field>
<button mat-raised-button color="primary" [disabled]="!loginForm.valid">Submit</button>
</form>
Мои .ts:
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder, Validators, FormControl } from '@angular/forms';
import { PasswordValidator } from './password.validator';
@Component({
selector: 'app-inscription',
templateUrl: './inscription.component.html',
styleUrls: ['./inscription.component.scss']
})
export class InscriptionComponent implements OnInit {
loginForm : FormGroup;
constructor() {}
ngOnInit() {
this.loginForm = new FormGroup({
user: new FormControl(null, [Validators.required]),
email: new FormControl(null, [Validators.required, Validators.email]),
password: new FormControl('', Validators.compose([
Validators.minLength(6),
Validators.required,
])),
confirm_password: new FormControl('', Validators.required)
}, (formGroup: FormGroup) => {
return PasswordValidator.areEqual(formGroup);
});
}
onSubmit(objValue) {
console.log(this.loginForm.valid);
console.log('objValue',objValue);
}
getErrorMessage(formControlName : string): string {
const errors : any= {
required : "Required Information",
minlength: "The password need at least 6 characters",
email : "The mail is not valid",
areEqual:"The passwords are not the same"
}
return Object.keys(this.loginForm.controls[formControlName].errors).reduce(
(prev, current, currentIndex) => {
return `${errors[current]}`;
},''
)
}
}
Мой сервис:
import { FormControl, FormGroup, NgForm, FormGroupDirective } from '@angular/forms';
export class PasswordValidator {
static areEqual(formGroup: FormGroup) {
let password;
let passwordconfirmation;
let valid = true;
for (let key in formGroup.controls) {
if(key === password && password !== undefined){
password = formGroup.controls[key].value
}
if(key === confirm_password && confirm_password !== undefined){
passwordconfirm = formGroup.controls[key].value
}
}
if (password !== confirmpassword) {
valid = false;
}
if (valid) {
return null;
}
return {
areEqual: true
};
}
}