Hello, Magento folks,

Last time, we talked about how you can remove disabled products from the cart page in Magento 2. Today we are going to learn about how to create custom UI components using knockout.js in Magento 2.

Knockout or KO is a library of JavaScript files. It is mostly used in the frontend part of the Magento 2 especially in checkout pages. With the introduction of this library, it has been made possible to create responsive frontend components like date picker, popup, and other UI components.

UI components are a large and complex topic in Magento 2. They are used to create elements like tables, buttons, tabs, dialogs, and more. Let me be more specific, a UI component is used to implement a part of the MVVM model. For today, I will let you know how we can create a custom UI Component template with the help of codes.

First, let’s look at the Flow:

Step 1: We will create one PHTML file

Step 2: Create custom component over there using “Magento_UI/js/core/app”

Step 3: Register New Component within Components

Step 4: Call out custom component template file and pass the variable.

Step 5: In js file, we will put the KO library for knockout js.

Step 6: Return function is compulsory, so we put it and put our logic out there

Step 7: Now, data will bind with our HTML tag with the help of the “data-bind” attribute.

Let us see an example.

1. First, create PHTML file at the below path,

app\code\Vendor\Extension\view\frontend\templates\uicomponent.phtml

Now use the below code:

2. Now, create js file at the below path,

app\code\Vendor\Extension\view\frontend\web\js\uicomponentjs.js

Use the below code,

Using the above codes, you will successfully implement custom UI Components with your PHTML file. If you had any problem while implementing the codes, then contact us at our support portal. We will be happy to help you.

Lastly, if you liked this article, then let us know in the comments section below. Also, share it with your colleagues and friends.

Happy coding!

Click to rate this post!
[Total: 13 Average: 4.2]