![](/img/trans.png)
[英]In Angular, can I bind the emited output of a component directly to a property?
[英]can i bind from event to custom component output
我有一个自定义组件
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>
问题是我可以像这样使用 rxjs fromEvent 函数从 ts 代码绑定它吗
.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 元素类的引用。 在这里,您是 Angular 组件的ViewChild
。 它没有nativeElement
属性。
所以直接订阅你不需要fromEvent
:
@ViewChild('systemInput') systemInput: SystemInputComponent;
ngAfterViewInit(){
this.systemInput.enterFn.subscribe(a => //a is the $event );
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.