Reputation: 67
i am having a custom component
export class SystemInputComponent implements OnInit, OnDestroy {
@Input() ...
@Output() enterFn: EventEmitter<any> = new EventEmitter<any>();
...
that has output that act as an event as i know
and that component imported outside in other component html
<div class="input-group">
<system-input #systemInput></system-input>
</div>
the regular way to bind the event is add it into the component tag as attribute with () and bind it to a function
<system-input #systemInput (enterFn)="someFunct($event)"></system-input>
the question is can i bind it from ts code with rxjs fromEvent function like this
inside .ts file
import { fromEvent } from 'rxjs';
.
.
..
@ViewChild('systemInput') systemInput:any;
ngOnInit(){
fromEvent(this.systemInput.nativeElement,'enterFn').subscribe(a => //a is the $event );
}
..
and if it could how to it properly, because it give me a error
Cannot read property 'nativeElement' of undefined
EDIT as JoH said in the first comment i moved it to ngAfterViewInit
ngAfterViewInit(){
fromEvent(this.systemInput.elementRef.nativeElement,'enterFn').subscribe(a => //a is the $event );
}
it give me that new error
Invalid Event Traget
Upvotes: 1
Views: 1232
Reputation: 11000
nativeElement
usually used to get a reference to the HTML element class. While here you ViewChild
of an Angular component. It doesn't have nativeElement
property.
So to subscribe directly you don't need fromEvent
:
@ViewChild('systemInput') systemInput: SystemInputComponent;
ngAfterViewInit(){
this.systemInput.enterFn.subscribe(a => //a is the $event );
}
Upvotes: 1