Angular 2 - 如何处理指令中的变化检测

时间:2018-02-13 17:16:11

标签: angular

我有一个输入字段,我附加了一个指令。

<input type="email" 
       id="email" 
       formControlName="email" 
       email
       [placeholder]>

该指令是占位符,当用户使用新值更新输入时,我想在指令中运行一些代码:

  @Input() public input: String;

  constructor(private el: ElementRef) {}

  @HostListener('change') ngOnChanges() {
    console.log('test');
  }

我以为我需要使用hostListener指令来检查更改,但这不符合我的预期。我的目的是在输入内部有一个值时添加一个类。

其他人如何做到这一点?

2 个答案:

答案 0 :(得分:1)

使用模板驱动表单并在模板中定义输入属性绑定,如下所示

 <input type="email" 
    id="email" 
    [(ngModel)]="email"
    [input]="email"  
    placeholder>

Directive.ts

     @Input() public input: String;
     constructor(private el: ElementRef) {}
     @HostListener('change') ngOnChanges() {
      console.log('test');
       }

它可能有所帮助,也可以查看这个例子 https://stackblitz.com/edit/angular-na4ncb?file=app%2Fapp.component.html

答案 1 :(得分:0)

您可以使用de OnChange

@Directive({
   selector: '[my-directive]'
})
export class MyDirective implements OnChanges {
   @Input('value-listen') public formControl: any;

   ngOnChanges(changes: SimpleChanges){
     console.log(changes);
   }

}

仅应在[value-listen] =“ yourValue”

中传递formControl