1. Context
Creating Web Components is possible in vanilla JS by:
- Creating a class that
extends
HTMLElement
- And then registering it:
window.customElements.define('app-drawer', AppDrawer);
Since I have a lot of code in Dart I thought I could maybe do that with it. But I've hit some obstacles. Mainly the facts that document.registerElement()
is deprecated and that window.customElements.define()
doesn't seem to work.
I mostly use Microsoft Edge as a browser. But it uses Chromium anyway. And I've also tested everything mentioned below on Chrome as well.
2. What I've Tried
2.1. Günter's Answer with document.registerElement()
Günter's answer points to this dartpad, which uses the document.registerElement()
to define it.
His answer does work, but document.registerElement()
is deprecated:
document.registerElement is deprecated and will be removed in M80, around February 2020. Please use window.customElements.define instead.
Or at least on my computer it works, because his DartPad actually gives back the error of NoSuchMethodError: method not found: 'registerElement'
2.2 Trying the same thing with window.customElements.define()
import 'dart:html';
main() {
try {
window.customElements.define('graph-button', GraphButton);
final GraphButton button = GraphButton();
document.body.append(button);
button.changeInnerHtml();
} catch (e) {}
}
class GraphButton extends HtmlElement {
static const String tag = 'graph-button';
factory GraphButton() => Element.tag(GraphButton.tag);
GraphButton.created() : super.created();
changeInnerHtml() => innerHtml = 'foo';
}
The code above will yield the following error message:
Error: Failed to execute 'define' on 'CustomElementRegistry': The callback provided as parameter 2 is not a function.
2.3. An Attempt with JS Interop
I've even tried to create an interop function for JS's window.customElements.define
, but the error was the same.
@JS('window.customElements')
library web_components_interop;
import 'package:js/js.dart';
@JS('define')
external void registerWebComponent(String name, Object constructor, [Map<dynamic, dynamic> options]);
Then simply replacing the registering above for registerWebComponent(GraphButton.tag, GraphButton);
will now yield the same error message.
3. Other Helpful Resources
Is there official documentation on this topic? I was hoping to find something about it on AngularDart's docs — since, in Angular, creating web components is quite common —, but I haven't been able to so far.