[英]Inject a formcontrol into a custom directive
I want to create a directive can change a host element when a form control invalid as code sample below: 我想创建一个指令,当表单控件无效时,可以更改宿主元素,如下面的代码示例所示:
<div [appFormControlValidate]="email"> <!-- email is the form control I want to inject -->
<input type="email" formControlName="email" />
</div>
@Directive({
selector: '[appFormControlValidate]'
})
export class FormControlValidateDirective {
@Input('appFormControlValidate') formControl: FormControl;
constructor(private el: ElementRef) {
console.log(this.formControl); // <-- give me undefine
}
}
Thanks. 谢谢。
Properties with @Input
decorator will be accessible at the OnInit
lifecycle, not in the constructor . 使用
@Input
装饰器的属性将在OnInit
生命周期中访问,而不是在构造函数中 。 When the property with @Input
is initialized, the OnChanges
event is called. 初始化带有
@Input
的属性时,将调用OnChanges
事件。 At this time the property has the passed value and after this event OnInit
is called once. 此时,该属性具有传递的值,并且在此事件之后,将调用一次
OnInit
。 So already at OnInit
you will receive the passed value. 因此,在
OnInit
您将收到传递的值。
@Directive({
selector: '[appFormControlValidate]'
})
export class FormControlValidateDirective {
@Input('appFormControlValidate') formControl: FormControl;
constructor(private el: ElementRef) {
}
ngOnInit() {
console.log(this.formControl);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.