2016-11-04 11 views
4

私はカスタムディレクティブで入力値を解析したいと思うangle-2 basicのカスタムディレクティブを試しています。角度2のカスタムディレクティブに入力データ値を送る方法は?

見てみましょう。

app.component.tsというアプリコンポーネントがあります。私は入力欄を取った。

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

次の私は、カスタムディレクティブ名は

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

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

をcustom.directive.ts今、私は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

ありがとうございました。その仕事.... –

関連する問題