DEV Community

Sudhakar George
Sudhakar George

Posted on

Integrating sg-autocomplete Component

Image description

What is sg-autocomplete Component?

sg-autocomplete component is a user interface element that functions like a text input field, but as the user types, it dynamically suggests relevant options from a predefined json list, allowing them to quickly select a matching value instead of typing the full term manually.

You can configure with any elements from the json file.

You can navigate the autocomplete dropdown using mouse or tab key from keyboard.

Getting Started

Use the below command to add your package in your application

npm i sg-autocomplete
Enter fullscreen mode Exit fullscreen mode

you can consume it in your application as shown below:

<sg-autocomplete autotext="JSON-ELEMENT-NAME"></sg-autocomplete>
Enter fullscreen mode Exit fullscreen mode

Say for Example if your JSON element is like this

{
    url: "https://cdn-icons-png.flaticon.com/512/1804/1804486.png", 
    title: "URL", 
    description:"URL"
  },
  {
    url: "https://i.ibb.co/7XqwsLw/fox.jpg",
    title: "Fox", 
    description:"Fox"
 },
Enter fullscreen mode Exit fullscreen mode

If you want to add "description" as the autocomplete suggestion list, you can do so like this

sg-autocomplete autotext="description"></sg-autocomplete>
Enter fullscreen mode Exit fullscreen mode

Options

Image description

Examples

Image description

Usage

Now we will see how to integrate this libiary in your applications.

a) Vanilla JavaScript

You can include the component in your HTML file in two ways:

1. Using a CDN:

Add a tag in the of your HTML file, pointing to the component's JavaScript file hosted on a CDN.

For example:

<script src="https://cdn.jsdelivr.net/npm/sg-autocomplete/dist/sg-autocomplete/sg-autocomplete.js"></script>
Enter fullscreen mode Exit fullscreen mode

2) Using ES Modules:
If you prefer to use ES Modules, you can import the component using an import statement:

 <script type="module">
   import { defineCustomElements } from './dist/sg- 
   autocomplete/loader/index.es2017.mjs';
   defineCustomElements();
 </script>
Enter fullscreen mode Exit fullscreen mode

Make sure to adjust the paths according to your project structure.

Use the component in your HTML:

You can now use the component in your HTML like any other HTML element:
Code

 <sg-autocomplete autotext="description" dropdown=true >
</sg-autocomplete>
Enter fullscreen mode Exit fullscreen mode

Interact with the component using JavaScript:

Example of Setting the JSON data:

 const autocompleteLst = [
        {url: "https://cdn-icons-png.flaticon.com/512/1804/1804486.png", title: "URL", description:"URL"},
        {url: "https://i.ibb.co/dBCHzXQ/paris.jpg", title: "Paris Eiffel", description:"Paris Eiffel"},
        {url: "https://i.ibb.co/JKB0KPk/pizza.jpg", title: "Pizza Time", description:"Pizza Time"},
        {url: "https://i.ibb.co/VYYPZGk/salmon.jpg", title: "Salmon ", description:"Salmon"},
      ];
      document.querySelector('sg-autocomplete').suggestionlist = autocompleteLst
Enter fullscreen mode Exit fullscreen mode

You can access and manipulate the component using standard DOM APIs:

 const input = document.querySelector('#sg-autocomplete');
Enter fullscreen mode Exit fullscreen mode

Handle events:

  input.addEventListener('click', function(event) {
  // Code to execute when the button is clicked
     console.log('Input Value:'+ event.target.value);
 });

  input.addEventListener("keydown", (e) => {
     console.log(e.key+'Input Value keydown:'+ e.target.value);
  }); 
Enter fullscreen mode Exit fullscreen mode

b) Angular

Step 1: Add an import to main.ts

import { defineCustomElements} from '../node_modules/sg-autocomplete/loader';
Enter fullscreen mode Exit fullscreen mode

And somewhere near the bottom we'll call this function.

defineCustomElements();
Enter fullscreen mode Exit fullscreen mode

Step 2: Next, in app.module.ts add the CUSTOM_ELEMENTS_SCHEMA.

import {CUSTOM_ELEMENTS_SCHEMA} from `@angular/core`;
Enter fullscreen mode Exit fullscreen mode

and then

schemas: [
    CUSTOM_ELEMENTS_SCHEMA
]
Enter fullscreen mode Exit fullscreen mode

Your app.module.ts should look like this:

import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';

@NgModule({
  declarations: [],
  imports: [],
  schemas: [ CUSTOM_ELEMENTS_SCHEMA],
  providers: [],
  bootstrap: [AppComponent]
})

export class AppModule { }
Enter fullscreen mode Exit fullscreen mode

Please Note: schemas: [ CUSTOM_ELEMENTS_SCHEMA ] need to be added to each component where you are using custom HTML tags.

Step 3: Declare the arrayData: In your Angular component's TypeScript file, declare the arrayData that you are passing.

 arrayData  =[{"url": "https://i.ibb.co/10fFGkZ/car-race.jpg", "title": "Car Racing", "description":"Car Racing"} , 
    {"url": "https://i.ibb.co/gM5NNJX/butterfly.jpg", "title": "Butterfly", "description":"Butterfly"},
    {"url": "https://i.ibb.co/ygqHsHV/coffee-milk.jpg", "title": "Coffee with Milk", "description":"Coffee with Milk"}];
  autotext  =this.arrayData ;
Enter fullscreen mode Exit fullscreen mode

Now, Set the arraydata value to the sg-autocomplete component

 ngOnInit() {
     const myElement = this.el.nativeElement.querySelector('sg-autocomplete');
      if (myElement) {
        myElement.suggestionlist =this.autotext;
      }
    }
Enter fullscreen mode Exit fullscreen mode

Step 4: Now, in app.component.html you utilize your new custom element.

   <sg-autocomplete autotext="description" dropdown=true></sg-autocomplete>
Enter fullscreen mode Exit fullscreen mode

Note: Here "description" is the JSON element name that will show it as a dropdown suggestion list.

Step 5: To consume the autocomplete value you can create function access it like this

 getValue() {
      const autocompleteValue = this.el.nativeElement.querySelector('sg-autocomplete') as HTMLInputElement;
    } 
Enter fullscreen mode Exit fullscreen mode

c) React

Step 1:
Now we'll add an import to index.js

import { defineCustomElements} from '../node_modules/sg-autocomplete/loader';
Enter fullscreen mode Exit fullscreen mode

And somewhere near the bottom we'll call this function.

defineCustomElements();
Enter fullscreen mode Exit fullscreen mode

Step 2:
Next, in app.js Pass the json array and utilize the new custom element,

function App() {
  const arrayData  =[{"url": 
    {"url": "https://i.ibb.co/gM5NNJX/butterfly.jpg", "title": "Butterfly", "description":"Butterfly"},
    {"url": "https://i.ibb.co/ygqHsHV/coffee-milk.jpg", "title": "Coffee with Milk", "description":"Coffee with Milk"},
    {"url": "https://i.ibb.co/7XqwsLw/fox.jpg", "title": "Fox", "description":"Fox"},
    ];

  const myElement = useRef(arrayData);
    useEffect(() => {
      if (myElement.current) {
        const element = myElement.current;
        document.querySelector('sg-autocomplete').suggestionlist = element;
      }
    }, []);
  return (
    <div>
          <sg-autocomplete autotext="description" dropdown="true"></sg-autocomplete>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

d) Vue

Add defineCustomElements to one of our main files. Specifically main.js for Vue.

import { defineCustomElements} from '../node_modules/sg-autocompleter/loader';
Enter fullscreen mode Exit fullscreen mode

And somewhere near the bottom we'll call this function.

defineCustomElements();
Enter fullscreen mode Exit fullscreen mode

Next, in App.Vue you consume the custom element.

<template>
  <div>
  <sg-autocomplete autotext="description" dropdown="true"></sg-autocomplete>
  </div>
</template>

<script>
    export default {
      data() {
        return {
        arrayData:[
            {"url": "https://i.ibb.co/gM5NNJX/butterfly.jpg", "title": "Butterfly", "description":"Butterfly"},
            {"url": "https://i.ibb.co/VYYPZGk/salmon.jpg", "title": "Salmon ", "description":"Salmon"},
            {"url": "https://i.ibb.co/10fFGkZ/car-race.jpg", "title": "Car Racing", "description":"Car Racing"}  
           ]
      }
   },
    mounted() {
      document.querySelector('sg-autocomplete').suggestionlist = this.arrayData;
    }
};
</script>
Enter fullscreen mode Exit fullscreen mode

Click Here for Vue application live demo.


Hope this article is useful to you and your project, If you like this article, like & share it with your friends.

Follow Me for more articles.

Top comments (0)