This tutorial will follow from the previous tutorial where actually rendered the model in the UI.
Now we would be adding a TextBox and a button.
1. Add TextBox and a Button
Currently, our view function displays only a text which is the value coming from the model.
Now we want the view to display a TextBox as well as a button. To achieve that you need to modify the view function like so.
view model = div [] [ text(fromInt model.value), div [] [], input [] [], button [] [text "Add"] ]
Also note that I have added an empty div just after the number displayed.
Note you need to do the following:
- Add input and button to the import Html statement
- Import String exposing fromInt function
You can watch the video for the step by step
2. Add a ClickHandler to the Button
To achieve this, we first need to take four steps:
Step 1 – Import onClick() from Html.Events. The import below does it:
import Html.Events exposing (onClick)
Step 2 – Add OnClick as first parameter to the button like so:
button [onClick Add] [text "Add"]
The onClick expects a parameter which is of type message. Here we call the message Add.
Step 3 – Create a message. A message is anything that can be done that affects the model. So we create a message just after the add function like so:
type Messages = Add
Step 4 – Since the click would modify the model we must give the update function the message as a first parameter. Then it returns the updated model. For now, we just return the same model. So modify the update function like so:
update msg model = case msg of Add -> model
Cool! Let’s now talk about logging.
3. Logging Messages to the Console
Logging some text to the console is in Elm is a bit different that how it is done in JavaScript or Angular.
In Elm, logging is kind of considered a side effect, and so in pure functional language like Elm, it is not normally welcome. However, it could be necessary at time.
Let modify our code to log some text to the console when a button is clicked. Follow the steps:
Step 1 – Import Debug like so:
import Debug exposing (log)
Step 2 – In the updated function, write the code to log some message enclosed in a let … in block. This is shown below:
update msg model = let logmessage = log "here" "Button Clicked" logmessage2 = log "model" model in case msg of Add -> model
What happens here is that when the button is clicked, the update function is called with the parameters: msg and model. Then the content of the let … in block is executed.
Now go ahead to recompile the code and test it out in the browser with the console window open
You will notice that the text “Button Clicked” is displayed. Also the model is logged as well.
If you’ve come this far, congrats!
In the next part, we would then see how we can grab the text entered in the text field and use it to update our model.