1

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
Hassan Ahmed
  • 67
  • 1
  • 12
  • Move `fromEvent(this.systemInput.nativeElement,'enterFn').subscribe(a => //a is the $event );` in `ngAfterViewInit()` method. You need to implement `AfterViewInit` interface. – JoH Sep 09 '20 at 08:59
  • i did it but it can't recognize the target, it gave me that error **Invalid event target** – Hassan Ahmed Sep 09 '20 at 09:03
  • where is your someFunct() method, that you are triggering? Can you show its definition? – Wahab Shah Sep 09 '20 at 09:19
  • my problem isn't with the someFunct($event) method, what i am trying to do is bind the event with **fromEvent** from rxjs to replace the regular use of it – Hassan Ahmed Sep 09 '20 at 09:22

1 Answers1

1

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 );
}
Julius Dzidzevičius
  • 10,775
  • 11
  • 36
  • 81