custom-elements-ts
Create native custom elements using Typescript without using any third party libraries.
npm install custom-elements-ts
Usage
;
<!--index.html-->
Decorators
Decorator | Target | Parameters | Description |
---|---|---|---|
@Prop() | property | - | custom attribute/properties, reflects primitive properties to attributes |
@Toggle() | property | - | boolean attribute/properties, it is based on the presence of the attribute but also works with "true" and "false" |
@Dispatch() | property | (event?) | used to declare a CustomEvent which you could dispatch using the .emit method of its type DispatchEmitter . The event parameter is used to set the name of the CustomEvent |
@Watch() | method | (property) | triggers the method when a property is changed |
@Listen() | method | (event, selector?) | listens to an event on the host element or on the selector if specified |
@Prop()
;
Since color
is a primitive type of string
it can be accessed via attributes and properties
;// accessing value via attribute;// setting value via attributeelement.setAttribute'color', 'red'; // accessing value via property;// setting via propertyelement.color = 'red';
On the other hand list
is a rich data type (objects or arrays) can only be accessed/set via property
@Toggle()
Toggle attributes work the same way as HTML boolean attributes as defined by W3C for the most part. We changed a few things to overcome confusion. Check the table below for reference:
Markup | disabled |
Description |
---|---|---|
<c-input /> |
false | Follows W3C standard |
<c-input disabled/> |
true | Follows W3C standard |
<c-input disabled="true"/> |
true | Follows W3C standard |
<c-input disabled="asd"/> |
false | false since asd does not evaluate to a valid boolean |
<c-input disabled="false"/> |
false | false since the boolean false converted to a string is "false" |
<c-input disabled="true"/> |
true | true since the boolean true converted to a string is "true" |
@Dispatch()
Creating a custom event
; ...
Triggering the custom event from the example above:
triggerOnChange
@Watch()
; ...
@Listen()
Listen has parameters event
and selector
. Event
is any valid javascript event. Selector
is anything that works with querySelector()
; ...
Setup
Running the demos
npm start <element-name>
Building the demo
npm run build <element-name>
If you want to create a minified bundle
npm run build -- <element-name> --prod