如何从指令注册到Angular2中的组件输入?从指令发送数据到Angular2组件
具体而言,我已经知道this solution,但我想这样做没有父母的包围。
我从Angular2网站这个片段中的代码,但我无法得到它的工作将数据发送到组件:
// 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>
我终于结束了这个解决方案,这那不好,但我仍然认为input
更好。
请如果有人有更好的解决方案发布它。
http://plnkr.co/edit/FZsIfLfvtf3EjkGGGBlC
当你说“不能得到它的工作”你的意思是你不看控制台日志? – happyZZR1400
不。他们从来没有被绑定,我知道我可以在外面定义一个回调,并将其设置为'Simple'组件以从'Directive'发送数据并发送到'Simple'输入,但是我想订阅直接从'dirTest'输入。 – PRAISER