2016-11-04 41 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

感謝哥們。它的工作.... –

相關問題