angular - 在 Angular 中为模板驱动的表单应用表单验证
问题描述
我一直在尝试向我的模板驱动表单添加功能,这将使用Angular 文档检查密码是否相等,但似乎在将验证器指令应用于我的表单后,验证甚至不会触发。我的代码:
注册组件.ts
export const matchingPasswordValidator: ValidatorFn = (control: FormGroup): ValidationErrors | null => {
const password = control.get('password');
const confirmPassword = control.get('confirmPassword');
return password.value === confirmPassword.value ? { passwordMatch: true } : null;
};
@Directive({
selector: '[matchingPassword]',
providers: [{ provide: NG_VALIDATORS, useExisting: MatchingPasswordValidatorDirective, multi: true }]
})
export class MatchingPasswordValidatorDirective implements Validator {
validate(control: AbstractControl): ValidationErrors {
return matchingPasswordValidator(control);
}
}
@Component({
selector: 'app-register',
templateUrl: './register.component.html',
styleUrls: ['./register.component.css']
})
export class RegisterComponent implements OnInit {
registerPost: RegisterPost = new RegisterPost();
register.component.html
<form #registerForm="ngForm" matchingPassword>
<mat-form-field>
<mat-label>Email</mat-label>
<input matInput [(ngModel)]="registerPost.email" name="email" #email="ngModel" email required>
<mat-error *ngIf="email.errors?.email">
Enter a valid email address
</mat-error>
</mat-form-field>
<mat-form-field>
<mat-label>Hasło</mat-label>
<input type="password" matInput [(ngModel)]="registerPost.password" name="password" #password="ngModel"
required>
</mat-form-field>
<mat-form-field>
<mat-label>Powtórz hasło</mat-label>
<input type="password" matInput [(ngModel)]="registerPost.confirmPassword" name="confirmPassword"
#confirmPassword="ngModel" required>
<mat-error *ngIf="registerForm.errors?.passwordMatch">
Password does not match.
</mat-error>
</mat-form-field>
<button type="submit" mat-stroked-button color="primary" (click)="!registerForm.valid || register()"
[loading]="registerClicked">
Register
</button>
</form>
解决方案
推荐阅读
- .htaccess - .htaccess 将 example.com/store/page.html 重写为 domain.com/page.html
- android - Android BLE onScanFailed 与三星手机中的状态 2
- angularjs - Protractor Jasmine 中的异常或错误处理
- excel - 将用户定义的范围插入另一个工作表
- python - 无法解析导入时的 Python 路径
- oauth - OAuth - Facebook 和 co 收集数据的另一种方式?
- java - 错误 org.apache.thrift.transport.TSaslTransport - SASL 协商失败 javax.security.sasl.SaslException:GSS 启动失败
- xml - Android Studio:我的所有 XML 文件都没有出现预览渲染
- google-cloud-platform - 如何在自定义域上运行 bitnami debian 9 内置组件 cakephp
- javafx - 如何仅在数据开始时显示 XYChart JavaFX(不显示状态 0)