Pax*_*rce 10 typescript angular-directive angular
我想通过自定义指令将验证器动态添加到我的 FormControl。
@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>
Run Code Online (Sandbox Code Playgroud)
我不需要引用 nativeElement(通过 ElementRef)。
我想引用 formControl ...
... 并使用它:
// 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);
}
Run Code Online (Sandbox Code Playgroud)
有任何想法吗?
谢谢你们。
小智 11
这是使用指令将验证器附加到表单控件的示例。
请注意,使用它会导致丢失所有以前的验证器。
constructor(
// Get the control directive
private control: NgControl
) { }
ngOnInit() {
const abstractControl = this.control.control;
abstractControl && abstractControl.setValidators([Validators.required]);
}
Run Code Online (Sandbox Code Playgroud)
如果您使用 NgControl 和构造函数 DI 注入,我们可以有一个指令适用于 formControlName 或模板驱动表单中来自反应式表单的表单控件:
指示:
import { Directive } from "@angular/core";
import { NgControl } from "@angular/forms";
@Directive({
selector: '[my-directive]'
})
export class MyDirective {
constructor(private el: ElementRef, private control : NgControl) { }
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
14441 次 |
最近记录: |