Reputation: 4617
I have an input text field like this
<input type="text" class="form-control" [inputTextFilter]="A" [ngModel]="name">
and my directive is:
import { Directive, Input, HostListener } from '@angular/core';
@Directive({
selector: '[inputTextFilter]'
})
export class InputTextFilterDirective {
@Input('inputTextFilter') params: string;
@HostListener('keypress', ['$event'])
onKeyUp(event: KeyboardEvent) {
console.log('got parameters: '+this.params);
}
}
and I have created a Directive called "inputTextFilter" to which I want to pass the "A" parameter. My passed parameter always shows as undefined.
Upvotes: 18
Views: 38138
Reputation: 1
In case anyone is still getting undefined inside the directive after following the accepted awnser, be sure that you're trying to access the variable inside ngOnInit not on the constructor.
The constructor of the directive is called before Angular initializes the directive's inputs.
Upvotes: 0
Reputation: 4617
In the hope that this helps someone else...the problem is in the template.
When I pass the input as [myDirective]="A" the A is being intpreted as an undefined variable. Since I wanted to pass the letter A I should have said [myDirective]="'A'"
Upvotes: 6
Reputation: 2339
Try this.
import {Directive, SimpleChanges} from '@angular/core';
@Directive({
selector: '[inputTextFilter]'
})
export class MyDirective {
@Input('inputTextFilter') params: string;
constructor(){}
ngOnInit(){
console.log(this.params)
}
}
Upvotes: 23
Reputation: 11184
Try like this in directive :
import {Directive, Input, ElementRef} from 'angular2/core';
@Directive({
selector: '[inputTextFilter]'
})
class FocusDirective {
@Input() inputTextFilter: any;
protected ngOnChanges() {
console.log('inputTextFilter', this.inputTextFilter);
}
}
Upvotes: 4