我在我的项目中实现了这个解决方案 http://blog.rangle.io/angular-2-ngmodel-and-custom-form-components/ 基本上你用表单元素构建一个组件并将其放入表单,我遇到的问题是当我想构建一个验证器来检查字段之间的依赖性时
import {Directive, Attribute} from '@angular/core';
import {
NG_VALIDATORS,
AbstractControl,
} from '@angular/forms';
@Directive({
selector: '[validateEqual][ngModel]',
providers: [
{provide: NG_VALIDATORS, useExisting: ParentFieldNotNullValidator, multi: true}
]
})
export class ParentFieldNotNullValidator {
constructor(@Attribute('validateEqual') public validateEqual: string) {
}
validate(c: AbstractControl): {[key: string]: any} {
if (!c.value) {
return null;
}
let e = c.root.get(this.validateEqual);
if (e && e.value) {
console.log('ERROR 1');
return null;
}
console.log('error 2');
return {validateError: "message"} }}
在常规模板驱动形式中它可以工作,但在这个实现中它没有,我得到了这种流 screenshot from webbrowser
当父字段存在且不为空时,此验证器应仅写入“ERROR 1”
我做错了什么? 我的 html:
<form #form="ngForm" (ngSubmit)="onSubmit(form.value)">
<div class="u-space-bottom-8">
<form-input
cannotContainSpace
minlength="4"
required
name="username"
[(ngModel)]="user.username">
>
</form-input>
</div>
<div class="u-space-bottom-8">
<form-input
validateEqual="username"
type="password"
required
name="password"
[(ngModel)]="user.password">
>
</form-input>
</div>
<button
class="c-btn c-btn--default u-h-10 u-bg-gray-16 u-paint-white-1"
type="send"
[disabled]="!form.valid"
>
{{'btn_login'|translate}}
</button>
</form>
最佳答案
我找到了一个解决方案,问题出在数据绑定(bind)上,现在我的验证器看起来像这样:
import {Directive, Input} from '@angular/core';
import {
NG_VALIDATORS,
AbstractControl,
} from '@angular/forms';
@Directive({
selector: '[validateEqual][ngModel]',
providers: [
{provide: NG_VALIDATORS, useExisting: ParentFieldNotNullValidator, multi: true}
]
})
export class ParentFieldNotNullValidator {
constructor() {
}
@Input('validateEqual') parentValue: string;
validate(c: AbstractControl): {[key: string]: any} {
if (!c.value) {
return null;
}
if (this.parentValue) {
return null;
}
return {parentFieldNotNull: "message"}
}
}
和 html 看起来像这样
<form #form="ngForm" (ngSubmit)="onSubmit(form.value)">
<div class="u-space-bottom-8">
<form-input
cannotContainSpace
minlength="4"
required
name="username"
[(ngModel)]="user.username">
>
</form-input>
</div>
<div class="u-space-bottom-8">
<form-input
[validateEqual]="user.username"
type="password"
required
name="password"
[(ngModel)]="user.password">
>
</form-input>
</div>
<button
class="c-btn c-btn--default u-h-10 u-bg-gray-16 u-paint-white-1"
type="wyslij"
[disabled]="!form.valid"
>
{{'btn_login'|translate}}
</button>
</form>
关于angular 2 表单元素作为组件 - 验证不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43339751/