2017-06-03 40 views
0

如何从指令注册到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 
+0

当你说“不能得到它的工作”你的意思是你不看控制台日志? – happyZZR1400

+0

不。他们从来没有被绑定,我知道我可以在外面定义一个回调,并将其设置为'Simple'组件以从'Directive'发送数据并发送到'Simple'输入,但是我想订阅直接从'dirTest'输入。 – PRAISER

回答

0

我能想到关于通过“输入”合格值与组分只从父容器:

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

当“mySub”和“name”是父容器的方法和属性:

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

看到这个plunk

+0

我已经更新了这个问题,而不是使用父项! – PRAISER

+0

你能把这里的链​​接放到代码片段吗? – happyZZR1400

+0

我不明白这个问题,什么代码片段? 您的意思是? https://angular.io/docs/ts/latest/guide/attribute-directives.html – PRAISER