2016-11-04 78 views
4

我正在试验angular-2基本自定义指令,我想在自定义指令中解析输入值。如何将输入数据值发送到angular-2中的自定义指令?

让我们来看看。

我有一个名为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 ...我如何分析数据只是对每按一次键..?

请给我建议任何人......

回答

3
@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()对于这种情况不是必需的,因为它不是在此使用的角度绑定。

Plunker example

这应该工作以及和更容易使用:

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

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

Plunker example

+0

我想打印针锋相对按键。以上代码无法正常工作。无论我通过键盘输入什么内容,它都将使用自定义指令显示在控制台中。 –

+0

在AppComponent中有'myInput'属性吗? –

+0

感谢哥们。它的工作.... –

相关问题