Let’s consider a very simple example. The project consists of two files: index.html
and alert-button.html
.
-
alert-button.html
defines a Polymer component. -
index.html
uses this component.
See the source code and the result below.
Tip
|
You can play with the example in an application created and deployed by Studio by copying the below files to your |
<html>
<!-- index.html is an entry point of our application. -->
<!-- Usually it loads one root Polymer element which contains all other components. -->
<head>
<!-- Import of a web component we want to use. -->
<link rel="import" href="src/polymer-basic/simple-component/alert-button.html">
<!-- Polyfills. -->
<!-- Natively web-components work only in Google Chrome. -->
<!-- For all other browsers polyfills are required. -->
<script src="bower_components/webcomponentsjs/webcomponents-loader.js"></script>
</head>
<body>
<alert-button>
<!-- This text goes to the <slot/> element of the Polymer component. -->
Our first simple component - alert button!
</alert-button>
</body>
</html>
link:../../../../source/polymer-build/src/polymer-basic/simple-component/alert-button.html[role=include]
Result
So, alert-button
is a component that is represented by a button and an optional caption. On click, the button shows the "Hello, User!" message. The code using this component provides a content in
the <alert-button/>
tag. This content is displayed by the slot
element inside the component. However, the slot
element is not required and can be omitted.
These are the basics that allow you to write and use simple Polymer components.
Tip
|
|
- What we have learned so far
-
-
Polymer components are declared in HTML files inside the
dom-module
tag. -
Each Polymer component file can contain CSS (optional), HTML (optional) and JavaScript (mandatory).
-
A Polymer component is declared by creating a class that extends
Polymer.Element
and registering it withcustomElements
object. Our web component must contain theis
static property which has to match the id of thedom-module
element. This id is used to refer to the component afterwards. -
Polymer component class can contain an arbitrary number of functions that can be called in handlers from HTML.
-
CSS declared in Polymer components don’t affect the rest of the application.
-
Polymer components can import and use other Polymer components.
-