In the previous article I explained what I mean when I say
In this article I'm going to dig a little deeper and get a little more concrete with a simple example.
These examples use TypeScript, so if you're using CodePen.io (which I suggest, at least for the first few examples until we start putting together a full stack application) then change your
TypeScriptpre-processor, and also add the
For starters, lets create a simple HTML page with the following body:
And lets add the following code:
In this example, the
firstName variable is an observable string value which changes every time the user changes the value of the
firstName input text box.
Breaking it down in more detail:
document.querySelector('#firstName')gets the input text box DOM element.
fromEvent(domElement, 'input')creates an observable on the
inputevent for the specified
At this point, if you had stopped there, then subscribing to the observable would pass the event to the observer. As it is, this event is what is also passed to the pipeline.
.pipe()creates a pipeline with a list of operators.
map(event => event.target.value)operator converts the event to the string value, so any subsequent pipeline operators will be operating on the string value, not the original event.
The next section of code subscribes to the
Observable<string> and sends the string to the
firstName .subscribe((value) => console.log(value));
When you run this full example, every time you change the value of the input text box, the new value is displayed in the console.
If you want to play with this, check it out on CodePen.