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
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.