User Actions
A user interface is said to be interactive, components need to respond to the various
actions like user click, hover and submission of form, etc. In the following example,
adding a click event for the component. Add a button to the component and set a click
for that.
The component template is defined as follows:-
static template = xml`
<div class="bg-info text-center">
<span class="mr-4">Hello Owl</span>
<button t-on-click="increment">
Click Me! [<t t-esc="state.value"/>]
</button>
</div>`;
Next is to add the on-click function increment as given below:-
class Counter extends Component {
static template = xml`
<div class="bg-info text-center">
<span class="mr-4">Hello Owl</span>
<button t-on-click="increment">
Click Me! [<t t-esc="state.value"/>]
</button>
</div>`;
state = useState({ value: 0 });
increment() {
this.state.value++;
}
}
The output will be like this.
In the above-given example, a button is defined inside the component, and added an
on-click function for that button. When we click on the button, the value 0 will be
changed to 1, and for each click the value will be increased by 1. After refreshing the
page, the value will be reset to 0. In the first step, we defined the template for the
component and added the t-on-click attribute for the button in the component. The
attribute will bind the click event, and the value will be the name of the method. In
the given above example, the increase is the response function. In the second step, the
response function is defined inside the component. The event syntax of the component is
as follows:-
t-on-<name_of_the_event>=”method name in component”