0

I have an issue with attribute directive.

I have defined following directive:

import {Directive, Input, ElementRef} from 'angular2/core';
@Directive({
    selector: '[chooseMe]'
})

export class ChooseMe {
    @Input('chooseMe') data: string;
    constructor(private _elementRef:ElementRef) {
    console.log(this.data);    
}
}

And I hook it like that:

<button [chooseMe]="example"> W/E</button>

And of course, in my component I have:

@Component({
...,
directives:[ChooseMe]
})

However, each time this.data is undefined. Where is my mistake?

1 Answer 1

1

Inputs are not set before ngOnChanges() was called the first time.
ngOnInit() is called after the first ngOnChanges():

import {Directive, Input, ElementRef} from 'angular2/core';
@Directive({
    selector: '[chooseMe]'
})
export class ChooseMe {
    @Input('chooseMe') data: string;
    constructor(private _elementRef:ElementRef) {
    }

    ngOnInit() {
        console.log(this.data);    
    }
}
Sign up to request clarification or add additional context in comments.

5 Comments

Gunter is correct - just check it with your code - plnkr.co/edit/UoE1mIvfympVxPe6rNtd?p=preview
Maybe example is still undefined?
@GünterZöchbauer, you are right - I want to pass plain string. is it possible?
[chooseMe]="'example'" or chooseMe="example"
Thanks @micronyks for fixing the typo and the Plunker :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.