that is my angular ts file where i write my logic
ngAfterViewInit() {
fromEvent(this.addBtn?.nativeElement,'click').subscribe(res=>{
console.log('response for the fromElement',res);
this.appendElement()
})
}
addItem(){
this.appendElement();
}
appendElement(){
let el = document.createElement('li') ;
el.innerText="Future web";
// @ts-ignore
document.getElementById('listContainer').appendChild(el);
}
that is my html file
<Button #addBtn>From Event</Button>
<button (click)="addItem()">Inside </button>
<ul id="listContainer">
</ul>
In the above code, I generate dynamic li and display in the list but I'm not able to get the exact difference between both
CodePudding user response:
The basic difference b/w the two is that:
fromEvent is an Observable that emits events of a specific type coming from the given event target. It is part of rxjs library. https://rxjs.dev/api/index/function/fromEvent
While the click event is actually an angular created wrapper for the normal HTML click DOM event.
For minor use cases as above, click event will be the right way to go where you are expecting the trigger from specific known elements.
CodePudding user response:
fromEvent is rxJs function used to create Observable
from DOM events. Hence it allows us to use all RxJs powerful features. It's very useful when you want to do some computation work on events.
We can even combine two or more Observables created by two or more DOM Nodes events.
One of the common use cases of fromEvent
is when you want to reduce API calls while searching on our webpage.
fromEvent
is also useful when you want to listen to events on multiple DOM Nodes. You can just pass the ArrayLike Nodes list as a first parameter.
(click)
is the normal click event just like in JavaScript, which triggers every time users click on a target DOM node. more here
So comparing both use fromEvent
when you want to perform some operation on DOM events