カスタムディレクティブの入力値を解析したいangular-2basicのカスタムディレクティブを実験しています。
みてみましょう。
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);
}
しかし、それは正しく機能していません。undefineを印刷しています。
私の懸念は...
1 ...キーを押すたびにデータを解析する方法..?
誰か提案してください...
@Directive ({
selector : '[customDir]',
exportAs: 'customDir' // <<<=== added
})
export class CustomDirective{
myInput : any;
}
のように使用します
<input customDir #customDir="customDir" [(ngModel)]="myInputInApp" (ngModelChange)="customDir.myInput = $event"/>
1つ目customDir
は、ディレクティブを適用することです。
#customDir="customDir"
ディレクティブへの参照を持つテンプレート変数を作成することです(requires exportAs
)
[(ngModel)]="customDir.myInput"
テンプレート変数#customDir
とそのプロパティによって参照されるディレクティブにバインドしますinput
。@Input()
ここで使用されているのはAngularバインディングではないため、この場合は必要ありません。
これも同様に機能し、使いやすくなります。
@Directive ({
selector : '[customDir]',
})
export class CustomDirective{
@HostListener('ngModelChange', ['$event'])
onModelChange(event) {
console.log(event);
}
}
<input customDir [(ngModel)]="someOtherProp"/>
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加