【问题标题】:Send data to Angular2 component from a Directive从指令向 Angular2 组件发送数据
【发布时间】:2017-11-05 00:10:26
【问题描述】:

如何从指令注册到 Angular2 中组件的输入?

具体来说,我已经知道this solution,但我想在没有父包的情况下这样做。

我有这个来自 Angular2 站点的 sn-p 代码,但我无法让它工作以向组件发送数据:

// 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

【问题讨论】:

  • 当您说“无法正常工作”时,您的意思是您没有看到控制台日志?
  • 没有。他们永远不会被束缚,我知道我可以在外部定义一个回调并将其设置为Simple 组件以从Directive 发送数据并发送到Simple 输入,但我想直接从dirTest.

标签: angular data-binding directive eventemitter


【解决方案1】:

我可以考虑仅从父容器通过“输入”将值传递给组件:

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

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

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

看到这个plunk

【讨论】:

猜你喜欢
  • 2017-07-31
  • 2018-03-31
  • 2016-12-26
  • 2016-07-24
  • 2020-05-10
  • 2016-08-09
  • 1970-01-01
  • 2016-07-28
  • 2018-09-01
相关资源
最近更新 更多