Angular:从指令访问 FormControl [英] Angular: access FormControl from Directive
本文介绍了Angular:从指令访问 FormControl的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想通过自定义指令将验证器动态添加到我的 FormControl.
I would like to add validators dynamically to my FormControl via a custom Directive.
@Directive({
selector: "[idNumber]",
})
export class IdNumberDirective implements OnInit {
constructor(private formControl: FormControl) { }
ngOnInit() {
this.addValidators(this.formControl);
}
addValidators(formControl: FormControl) {
formControl.setValidators(Validators.compose(
[Validators.required,
Validators.minLength(3),
Validators.maxLength(8)
]
));
}
<mat-form-field>
<mat-label>{{label}}</mat-label>
<input matInput
[formControl]="idNumberFormControl"
[placeholder]="placeholder"
</mat-form-field>
我不需要引用 nativeElement(通过 ElementRef).
我想引用 formControl...
...并像这样使用它:
I don't need to reference the nativeElement (via ElementRef).
I would like to reference the formControl...
...and use it as such:
// HTML with my custom directive 'idNumber' ////////
<custom-input-string
idNumber
[name]="'idNumber'"
[label]="Id Number"
[placeholder]="">
</custom-input-string>
// TS ////////
@ViewChild(CustomInputStringComponent) child: CustomInputStringComponent;
ngAfterViewInit() {
setTimeout(() => {
this.child.insertIntoForm(this.signupForm);
}, 0);
}
有什么想法吗?
谢谢大家.
Any ideas?
Thank you all.
推荐答案
以下是使用指令将验证器附加到表单控件的示例.
Here is an example of using a directive to append validators to your form control.
请注意,使用它会导致丢失所有以前的验证器.
Note that using that will result in losing all of your previous validators.
constructor(
// Get the control directive
private control: NgControl
) { }
ngOnInit() {
const abstractControl = this.control.control;
abstractControl && abstractControl.setValidators([Validators.required]);
}
这篇关于Angular:从指令访问 FormControl的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文