How to create an AutoComplete input in Ionic 7?
I’ve been looking for a way to create an auto-complete input in Ionic 7. This I needed for my bespoke CLI (command line interface) for the wireframing application I’m developing.
A week or so ago, I added voice command to this Ionic Application, which enables one to dictate commands to the app and then it executes whatever is needed. You can see these videos on Youtube, Part 1 and Part 2.
The ion-input component does not expose the native input component, thus adding a “list” attribute and a <datalist> component to ion-input does not work. One needs another solution.
The CLI functionality I want to add must have a list of available commands so that when one types in the input, auto-complete is fired and one can then choose a command and press enter. This is depicted in Figure 2 below.
As one has noted, some of the items in the auto-complete list are “3”, “3 view”, “all properties” etc. A user will type a command in the section depicted in Figure 3.
To create this component, we used an ion-item, input, ion-button and ion-icon. The HTML code for this looks like this.
We used an ion-item to host the input component. In the input component we set an attribute called “list” to “txtautocompletelist”. To properly format the input, we added the “native-input sc-ion-input-md” class. This makes the input to be like any other normal ion-input component.
<ion-item id="itemautocomplete" detail="false"
fill="outline" shape="round"
style="padding-left:0px;padding-right:0px">
<input id="txtautocomplete" class="native-input sc-ion-input-md"
list="txtautocompletelist">
<ion-button id="button1" fill="clear" mode="ios" slot="end"
style="--padding-start: 0px; --padding-bottom: 0px;
--padding-end: 0px; --padding-top: 0px;">
<ion-icon id="button1_icon" slot="icon-only" name="send-outline"></ion-icon>
<datalist id="txtautocompletelist">
<option>b4x</option>
<option>SithasoIONIC7</option>
<option>Made with Love</option>
<option>WebApps</option>
</datalist>
</ion-button>
</ion-item>
The list is then created with the datalist tag and we use a collection of option tags to specify the list items.
The ion-item has a button icon in the end slot. This enables one to have a click event, which can then read the value of the input and process further.
One can then use JavaScript to clear the datalist options and add new ones according to their needs.
Happy coding.
Check me out on Github and on my YT Channel for more content.
Check out my other thread about Ionic7 Wireframes