I created a custom element, and want to send data / parameters to it:
my element code is:
class SaveBtn
name
is an optional argument. When you pass a value it is used for the text
attribute of the button.
I pass it just to a field (name
) in the elements class and set it to the the button in attached
.
When you use data-xxx
attributes you can use the dataset
getter.
I also changed the other code a bit. I think attached
is a better place to access attributes because then the element is already upgraded properly.
class SaveBtn extends HtmlElement {
static final tag = 'save-button';
factory SaveBtn([String name]) => (new Element.tag(tag) as SaveBtn)..name = name;
ButtonElement innerButton;
ShadowRoot shadow;
SaveBtn.created() : super.created() {
// Create a Shadow Root
var shadow = this.createShadowRoot();
// Create a standard element and set it's attributes.
innerButton = new ButtonElement();
shadow.nodes.add(innerButton);
}
String name;
@override
void attached() {
super.attached();
innerButton.text = name != null ? name : this.dataset['name'];
}
}
SaveBtn({String name, String width}) => (new Element.tag(tag) as SaveBtn)
..name = name
..style.width=width;
Below a solution proved to work.
factory SaveBtn() => new Element.tag(tag)
String name, width;
@override
void attached() {
super.attached();
innerButton.text = name != null ? name : this.dataset['name']
..style.width=width;
}
call the item as:
var btn = new SaveBtn()..name='save'..width='100%';
This is another solution that worked with me before reading the posted answers, I liked @Gunter answer and will adapt it.
class SaveBtn extends HtmlElement {
static final tag = 'save-button';
factory SaveBtn()=>new Element.tag(tag);
var shadow, btn;
SaveBtn.created() : super.created() {
shadow = this.createShadowRoot();
btn = new ButtonElement()
..text="save"
..style.height= '20px'
..style.borderBottom='1px solid #D1DBE9';
btn.text = this.getAttribute('data-name');
shadow.nodes..add(label)..add(btn);
}
Element launchElement(name){
btn.text= name;
return (shadow);
}
}
and called the element as:
var btn=new SaveBtn()..launchElement('click me');
You can simply add a new constructor for this that sets the data-name
attribute too:
class SaveBtn {
// ...
factory SaveBtn(String label) {
var btn = new Element.tag(tag);
btn.setAttribute('data-name', label); // Set properties/call methods here
return btn;
}
// ...
}