将窗体控件注入到自定义指令中



我想创建一个指令,当表单控件无效时可以更改主机元素作为下面的代码示例:

<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
  }
}

谢谢。

带有@Input装饰器的属性将在OnInit生命周期中访问,而不是在构造函数中。初始化具有 @Input 的属性时,将调用 OnChanges 事件。此时,该属性具有传递的值,在此事件之后调用一次OnInit。因此,在OnInit,您将收到传递的值。

@Directive({
  selector: '[appFormControlValidate]'
})
export class FormControlValidateDirective {
  @Input('appFormControlValidate') formControl: FormControl;
  constructor(private el: ElementRef) {
  }
  ngOnInit() {
     console.log(this.formControl);
  }
}

最新更新