2

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
PRAISER
  • 793
  • 7
  • 15
  • when you say 'cannot get it work' you mean you dont see the console log? – happyZZR1400 Jun 03 '17 at 20:41
  • No. They never get bound, I know that I can define a callback outside and set it to the `Simple` component to send data from `Directive` out and send into `Simple` input but I'd like to subscribe to the input directly from `dirTest`. – PRAISER Jun 03 '17 at 20:45

1 Answers1

0

i can think about passing value to component through "Input" only from parent container:

<simple dirTest (refresh)="mySub($event)" [refresh]="name"></simple>

When "mySub" and "name" is method and property of parent container:

  mySub($event){
    this.name = $event; 
 }

see this plunk

happyZZR1400
  • 2,387
  • 3
  • 25
  • 43