【问题标题】:Angular : Output a callback of my Custom directive event and subscribe to it in my componentAngular:输出我的自定义指令事件的回调并在我的组件中订阅它
【发布时间】:2019-03-12 00:37:28
【问题描述】:

在我的 Angular 应用下,我做了一个自定义指令:

@Directive({
  selector: '[appCustomEdit]'
})

export class CustomEditDirective implements OnChanges {

  @Input() appCustomEdit: boolean;
  private element: any;

  constructor(private el: ElementRef, private renderer: Renderer2) {
    this.element = el.nativeElement;
  }

  ngOnChanges(changes: SimpleChanges) {
    if (changes.appCustomEdit.currentValue) {
      const btnElement = (<HTMLElement>this.element)
        .querySelector('.dx-link-save');

      this.renderer.listen(btnElement, 'click', () => {
        alert('Buton was clicked')
      });
    }
  }
}

myComponent.html 我正在使用这个指令:

<div>
  <input [appCustomEdit]=true></input> 
</div>

我现在需要实现从指令输出的一些事件/可观察对象,以便我可以在 myComponent.ts 中订阅它并执行一些操作。

不知道该怎么做?

建议?

【问题讨论】:

  • 不确定是否有人会理解您的代码。你想从中得到什么:const btnElement = (&lt;HTMLElement&gt;this.element).querySelector('.dx-link-save');?在构造函数中注入的 ElementRef 您的按钮(即&lt;input&gt;)元素。您还在寻找什么?

标签: javascript angular angular5 angular2-template angular2-directives


【解决方案1】:

嗯,直接回答你的问题应该是这样的:

import {Directive, EventEmitter, HostListener, Output} from '@angular/core';

@Directive({
    selector: '[appCustomInput]'
})
export class CustomInputDirective {

    @Output()
    myCustomEvent = new EventEmitter();

    @HostListener('click')
    onClick() {
        this.myCustomEvent.emit();
    }

}

然后像这样使用它:

<div>
  <input appCustomInput (myCustomEvent)="onMyCustomEvent()"></input> 
</div>

但是,目前尚不清楚您要通过此实现什么目标,因此我不能说这是否可行。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-06
    • 2016-05-30
    • 1970-01-01
    • 2012-01-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多