Dynamically add a web component to a div


I started with the generating click-counter example. I made the click-counter into a library which I then imported into my main file. The click-counter component can be added manually by putting the appropriate HTML into the web page before running the program. However, I’ve been unable to find a way to dynamically add the click-counter web component to a div. My attempts have either ended in “Aw, snap!” errors or simply with nothing happening.

The click-counter (xclickcounter.dart):

library clickcounter;
import 'package:web_ui/web_ui.dart';

class CounterComponent extends WebComponent {
  int count = 0;

  void increment() {

The main HTML:

<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Sample app</title>
    <link rel="stylesheet" href="test1.css">

    <!-- import the click-counter -->
    <link rel="components" href="xclickcounter.html">

    <p>Hello world from Dart!</p>

    <div id="sample_container_id">
      <div is="x-click-counter" id="click_counter" count="{{startingCount}}"></div>

    <script type="application/dart" src="test1.dart"></script>
    <script src="packages/browser/dart.js"></script>

main file:

import 'dart:html';
import 'package:web_ui/web_ui.dart';
import 'xclickcounter.dart';

// initial value for click-counter
int startingCount = 5;

void main() {
  // no error for adding an empty button
  var button = new ButtonElement();

  // doesn't work (gives "Aw, snap!" in Dartium)
  query('#sample_container_id').append(new CounterComponent());

  // Nothing happens with this code. Nothing appears.
  // But I promise this same thing was giving Aw, Snap 
  // for a very similar program
  final newComponentHtml = '<div is="x-click-counter"></div>';

I tried added an empty constructor to click-counter but it still crashes.


I had the same issue.
See the example (not mine) at https://github.com/dart-lang/web-ui/blob/master/test/data/input/component_created_in_code_test.html and let me know if it works for you.


void main() {
  var element = query('#sample_container_id');
  appendComponentToElement(element, new CounterComponent() );

void appendComponentToElement(Element element, WebComponent component) {
  component.host = new DivElement();
  var lifecycleCaller = new ComponentItem(component)..create();

There’s more info at my web-ui@dartlang.org post: https://groups.google.com/a/dartlang.org/d/topic/web-ui/hACXh69UqG4/discussion

Hope that helps.

Answered By – lizard

Answer Checked By – Marilyn (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *