Web components explicit API's using class methods

Yonatan Kra
InstructorYonatan Kra
Share this video with your friends

Social Share Links

Send Tweet

In this lesson, you will learn how to create an explicit API using methods on the web component itself.

Instructor: [00:01] We'll start by creating a simple custom element. It's a class that extends HTML element. We'll add some HTML [inaudible] . We'll define the custom element on the window and use it in our HTML page. Refresh the page and see our [inaudible].

[00:21] What we'd like to do now is create an API to change the text and its color. One way to do that is to add functions to the component. I'll add the function changeTextColor() that accepts the color. As a best practice, I will save a reference to the header, and use this reference in our method to change the header's text color.

[00:45] Next I will create a changeText() method. It accepts the text and changes the header's inner text. We can refresh the page and get a reference to our custom element. We can now call the method on the element to use our new API. I'll use the changeText method to change the text to "Hello Egghead." In the same way, we can use the method to change the text color.

[01:11] To summarize, we've created a web component with some HTML. We've added two methods to the component itself. We got a reference, using querySelector(), to our custom element, and used the methods on the element to change the text and the color. You can create as many methods as you want to create more sophisticated APIs.