我可以从事件绑定到自定义组件输出吗



我有一个自定义组件

export class SystemInputComponent implements OnInit, OnDestroy {
@Input() ...
@Output() enterFn: EventEmitter<any> = new EventEmitter<any>();
...

具有作为事件的输出,正如我所知

以及在其他组件html 中外部导入的组件

<div class="input-group">
<system-input #systemInput></system-input>
</div>

绑定事件的常规方法是将其作为属性((添加到组件标签中,并将其绑定到函数

<system-input #systemInput (enterFn)="someFunct($event)"></system-input>

问题是,我能把它从ts代码中绑定到rxjs-fromEvent函数中吗

在.ts文件内

import { fromEvent } from 'rxjs';
.
.
..
@ViewChild('systemInput') systemInput:any;
ngOnInit(){
fromEvent(this.systemInput.nativeElement,'enterFn').subscribe(a => //a is the $event );
}
..

如果它能正确地处理它,因为它给了我一个错误

Cannot read property 'nativeElement' of undefined

编辑正如JoH在第一条评论中所说,我将其移至ngAfterViewInit

ngAfterViewInit(){
fromEvent(this.systemInput.elementRef.nativeElement,'enterFn').subscribe(a => //a is the $event );
}

它给了我新的错误

Invalid Event Traget

nativeElement通常用于获取对HTML元素类的引用。而在这里,你ViewChild的角度组件。它没有nativeElement属性。

因此,要直接订阅,您不需要fromEvent:

@ViewChild('systemInput') systemInput: SystemInputComponent;
ngAfterViewInit(){
this.systemInput.enterFn.subscribe(a => //a is the $event );
}

最新更新