@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 采取一些行动。
我想知道怎么做?
好吧,你的问题的直接答案如下:
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>
然而,现在还不清楚你想用这个来达到什么目的,所以我真的不能说这是不是一条路要走。