In this section, we will learn if statements in Alpine.js, including how to use else statements with the not equal to (!=)
operator. In Alpine.js, you can use only if statements within a template div.
Example 1
Simple use of x-if statement.
<div x-data="{show:true}">
<template x-if="show">
<div>Show Data if true</div>
</template>
</div>
Example 2
If statement with click event.
<div x-data="{show:false}">
<template x-if="show">
<div>Show Data if true</div>
</template>
<button @click="show=false">Click</button>
</div>
Better way
<div x-data="{show:false}">
<template x-if="show">
<div>Show Data if true</div>
</template>
<button @click="show=!show">Click</button>
</div>
Example 3
In alpine js there is no else statement. But we perform operation else using (=!) not equal to.
<div x-data="{show:false}">
<template x-if="show">
<div>Show Data if true</div>
</template>
<template x-if="!show">
<div>Show Data if false</div>
</template>
</div>
Example 4
if else with click event .
<div x-data="{show:false}">
<template x-if="show">
<div>Show Data if true</div>
</template>
<template x-if="!show">
<div>Show Data if false</div>
</template>
<button @click="show=!show">Click</button>
</div>
Note: You can use x-show directive. x-show is much simple and easy to use, you can see same example in below.
<div x-data="{show:false}">
<div x-show="show">
<div>Show Data if true</div>
</div>
<div x-show="!show">
<div>Show Data if false</div>
</div>
<button @click="show=!show">Click</button>
</div>