简体   繁体   中英

can i bind from event to custom component output

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

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 );
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM