如何将输入数据值发送到 angular-2 中的自定义指令?

How to send input data value into custom directive in angular-2?

我正在试验 angular-2 basic 的自定义指令,我想在我的自定义指令中解析输入值。

一起来看看

我有一个名为 app.component.ts 的应用程序组件。我在哪里输入了一个输入字段。

<input [(ngModel)] = "myInput"/> 

接下来我构建一个自定义指令名称custom.directive.ts

import { Directive, ElementRef, Renderer} from '@angular/core';

@Directive ({
  selector : '[customDir]'
})
export class CustomDirective{
  constructor(private el : ElementRef, private renderer: Renderer){ }
}

现在我想在“app.component.ts中输入任何内容并在我的自定义指令中解析它,通过它我可以简单地在控制台中打印它..

让我们重新修改我的代码...

<app.component.ts>
<input [(ngModel)] = "myInput" [customDir] = "myInput"/> 
<custom.directive.ts>
import { Directive, ElementRef, Renderer, Input} from '@angular/core';

@Directive ({
  selector : '[customDir]'
})

export class CustomDirective{
  @Input('customDir') myInput : any;
  constructor(private el : ElementRef, private renderer: Renderer){ }
     console.log(this.myInput);
  }

但是它不能正常工作。打印未定义..

我担心的是...

1...我如何根据每次按键解析数据..?

请给我推荐任何人...

@Directive ({
  selector : '[customDir]',
  exportAs: 'customDir' // <<<=== added
})
export class CustomDirective{
  myInput : any;
}

并像

一样使用它
<input customDir #customDir="customDir" [(ngModel)]="myInputInApp" (ngModelChange)="customDir.myInput = $event"/> 

第一个 customDir 是完全应用指令。

#customDir="customDir"是创建一个模板变量,该变量引用了指令(需要exportAs

[(ngModel)]="customDir.myInput" 绑定到模板变量 #customDir 及其 属性 input 引用的指令。本例不需要 @Input(),因为此处使用的不是 Angular 绑定。

Plunker example

这应该也能工作并且更容易使用:

@Directive ({
  selector : '[customDir]',
})
export class CustomDirective{

  @HostListener('ngModelChange', ['$event'])
  onModelChange(event) {
    console.log(event);
  }
}
<input customDir [(ngModel)]="someOtherProp"/> 

Plunker example