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

问题描述

我有一个自定义组件

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绑定到这样的EventEvent函数中吗

.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是一个Angular组件。它没有nativeElement属性。

因此,直接订阅无需fromEvent

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

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...