如何使用 Reactive Forms 分配 @Directive 的 @Inputs
How to assign @Inputs of a @Directive using Reactive Forms
我正在尝试使用 @angular/forms
中的 FormBuilder
创建响应式表单,但我偶然发现了一个关于自定义验证 @Directives、@Inputs 和 FormBuilder
的案例。
在下面的代码中,我有自己的自定义 MatchValidator 指令,问题是,如何在定义 FormGroup
时为 @Input 变量赋值?
// My custom Directive
@Directive( {
selector: "[cw-match]",
providers: [ { provide: NG_VALIDATORS, useExisting: MatchValidator, multi: true } ]
} )
export class MatchValidator implements Validator,OnChanges {
@Input() matchTo; // <— How to assign values to this properties using formBuilder?
@Input() control;
ngOnChanges( changes:SimpleChanges ) {
this.control.control.updateValueAndValidity( false, true );
}
validate( control:AbstractControl ):{ [ key:string ]:any; } {
if( !control.value ) return null;
return ( control.value === this.matchTo )? null : { "matchError": true };
}
}
// My component
@Component( /*… */)
export class UserDetailsComponent implements OnChanges, AfterViewInit {
constructor( formBuilder: FormBuilder ){
this.userDetailsForm = this.formBuilder.group( {
slug: [ "", SlugValidator ],
basicCredentials: this.formBuilder.group( {
username: [ "", Validators.required ],
password: [ "", MatchValidator ], // <— How can I assign the matchTo and control values the @Input properties of the directive asks for?
repeatPassword: [ "" ],
} )
} );
}
}
甚至可以使用 FormBuilder 分配验证 @Directive 的 @Input 值吗??
提前致谢:)
你不能。 @Input
属性专门用于模板绑定,而不是您想要的代码。
编辑:另外,angular实际上并不期望验证器可以"change its mind"基于被验证值以外的其他东西,所以即使有是一种在表单生成器中指定它的方法,它无论如何都不能正常工作。
我正在尝试使用 @angular/forms
中的 FormBuilder
创建响应式表单,但我偶然发现了一个关于自定义验证 @Directives、@Inputs 和 FormBuilder
的案例。
在下面的代码中,我有自己的自定义 MatchValidator 指令,问题是,如何在定义 FormGroup
时为 @Input 变量赋值?
// My custom Directive
@Directive( {
selector: "[cw-match]",
providers: [ { provide: NG_VALIDATORS, useExisting: MatchValidator, multi: true } ]
} )
export class MatchValidator implements Validator,OnChanges {
@Input() matchTo; // <— How to assign values to this properties using formBuilder?
@Input() control;
ngOnChanges( changes:SimpleChanges ) {
this.control.control.updateValueAndValidity( false, true );
}
validate( control:AbstractControl ):{ [ key:string ]:any; } {
if( !control.value ) return null;
return ( control.value === this.matchTo )? null : { "matchError": true };
}
}
// My component
@Component( /*… */)
export class UserDetailsComponent implements OnChanges, AfterViewInit {
constructor( formBuilder: FormBuilder ){
this.userDetailsForm = this.formBuilder.group( {
slug: [ "", SlugValidator ],
basicCredentials: this.formBuilder.group( {
username: [ "", Validators.required ],
password: [ "", MatchValidator ], // <— How can I assign the matchTo and control values the @Input properties of the directive asks for?
repeatPassword: [ "" ],
} )
} );
}
}
甚至可以使用 FormBuilder 分配验证 @Directive 的 @Input 值吗??
提前致谢:)
你不能。 @Input
属性专门用于模板绑定,而不是您想要的代码。
编辑:另外,angular实际上并不期望验证器可以"change its mind"基于被验证值以外的其他东西,所以即使有是一种在表单生成器中指定它的方法,它无论如何都不能正常工作。