Send data to Angular2 component from a Directive

Viewed 1568

How can I register to an Input of a component in Angular2 from a Directive?

To be specific, I already know about this solution, But I'd like to do this without parent envelopment.

I have this snippet code from Angular2 site, but I cannot get it to work to send data to the component:

// Directive
import { Directive, ElementRef, Input, Output, EventEmitter } from '@angular/core';

@Directive({ selector: '[dirTest]' })
export class dirTestDirective {
    @Output() refresh = new EventEmitter<number>();
    constructor(private element: ElementRef) {
        setInterval(() => {
            this.refresh.emit( Math.random() );
        }, 1000);
    }
}

// Component
import {
    Input,
    Output,
    Component,
    OnChanges,
    SimpleChanges,
} from '@angular/core';

@Component({
    selector: 'simple',
    template: '<div></div>',
})
export class SimpleComponent implements OnChanges {
    @Input() refresh: number;
    
    // This never gets triggered
    ngOnChanges(changes: SimpleChanges) {
        console.log(changes);
    }
}
<!-- Get this together -->
<simple dirTest></simple>

Eventually I ended up with this solution which is not that bad, but I still think the input is better.

Please if anyone has a better solution post it.

http://plnkr.co/edit/FZsIfLfvtf3EjkGGGBlC
1 Answers
Related