【问题标题】:Get value from eventEmitter from directive without HTML Template从没有 HTML 模板的指令中获取 eventEmitter 的值
【发布时间】:2021-12-01 16:19:54
【问题描述】:

首先,抱歉,如果这是重复的。我一直在寻找一些答案,但没有找到。让我解释一下我的问题。

我有一个指令

@Directive({
  selector: '[myOwnDirective]',
})
export class MyOwnDirective {
  @Input() set myOwnDirective(value: string) {
    // do Something
  }
  @Output() valueChange = new EventEmitter<any>();

  constructor(private el: ElementRef) {}
  
  // Some more logic which will at some moment trigger the EventEmitter

}

我想通过 hostBinding 将此指令注入自定义组件。

export class MyOwnComponent implements OnInit {
  @HostBinding('attr.myOwnDirective') myOwnDirective = new MyOwnDirective(this.el);

  constructor(private el: ElementRef){}

  ngOnInit() {
    this.myOwnDirective.myOwnDirective = 'someValue';
  }

如您所见,在 ngOnInit 挂钩中,我可以设置指令中的 @Input 参数,就像我通常在 HTML 模板中使用 [] 所做的那样。 但是我如何能够捕获通过 EventEmitter 发出的值

【问题讨论】:

  • 为什么不想在 HTML 中使用默认方法?
  • 我不能这样做,因为我必须使用该指令的地方之一是使用 ComponentFactoryResolver 呈现的,因此该元素无法在 HTML 模板中定位

标签: angular angular2-directives


【解决方案1】:

首先,不建议使用 new 运算符创建指令,该指令永远不会被注入到 Angular DI 中。 (但这是 Angular 团队正在考虑的未来功能https://angular.io/guide/roadmap#support-adding-directives-to-host-elements

对于您的问题,您不能只订阅 EventEmitter 吗?

this.myOwnDirective.valueChange.subscribe(v => console.log(v));

【讨论】:

  • 我已经尝试过了,但我无法捕捉到该事件,但我认为这与以下事实有关:由于某些原因,在使用 new 运算符注入指令时,它不起作用好吧。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-13
  • 1970-01-01
  • 2015-12-09
  • 1970-01-01
  • 2018-01-11
  • 1970-01-01
相关资源
最近更新 更多