onConnected

Runs a function after the component's markup is in its shadow root and refs are filled.

onConnected(fn: () => unknown): void
onConnected(() => {
  const chart = new Chart(refs.canvas, config);
  return () => chart.destroy();
});

Parameters

Parameter Type Meaning
fn () => unknown Runs once, after the first connection. If it returns a function, that function runs when the element is removed

Order on connection

  1. The script runs (defineProps, useState, …).
  2. Reactive CSS is bound.
  3. The markup is cloned, bound and appended to the shadow root, and refs fill.
  4. A delegated ref="control" is wired up.
  5. The parent's useChildren arrays refresh.
  6. onConnected hooks run in the order they were registered.

Moving the element does not run the hooks again. It keeps its state.

Example

Previewindex.htmlauto-focus.html
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>onConnected demo</title>
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@realmorg/realm@alpha/dist/realm.css">
  <script type="module" src="https://cdn.jsdelivr.net/npm/@realmorg/realm@alpha/dist/realm.js"></script>
</head>
<body>
  <import-element from="./auto-focus.html"></import-element>

  <auto-focus></auto-focus>
</body>
</html>
<custom-element name="auto-focus">
  <script>
    onConnected(() => {
      refs.field.placeholder = "Filled in by onConnected";
    });
  </script>

  <input ref="field" aria-label="Example field">
</custom-element>

Edit this page on GitHub · View as Markdown