> For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt.

# Renderer internals

This page explains how AngularLynx turns Angular's rendering calls into native Lynx elements. It's for contributors and the curious: you don't need it to build an app.

The source is in `packages/runtime/src/lib`, mainly `renderer/`, `lynx-document/`, `lynx-element/`, `router/` and `runtime.ts`.

## Two bundles from one source

Apps install `@blotch/angular-lynx-build`. Its builders add the internal build plugin, `@blotch/rsbuild-plugin-angular-lynx`, to [RSpeedy](/guide/glossary.md#rspeedy), Lynx's build tool. The plugin builds two entries for each of the app's:

| Entry               | Thread     | Starts from                                      | Output                 | `__MAIN_THREAD__` |
| ------------------- | ---------- | ------------------------------------------------ | ---------------------- | ----------------- |
| `main__main-thread` | Main       | Your `main.ts`                                   | `main-thread.js`       | `true`            |
| `main`              | Background | A generated entry with your background functions | `background-thread.js` | `false`           |

Both are packed into one [bundle](/guide/glossary.md#bundle), `main.lynx.bundle`.

- **`__MAIN_THREAD__`** is replaced with each half's value as the plugin compiles. So shared code can check which thread it runs on, and the other thread's branch is left out.
- **Your stylesheets** are taken from the main-thread half, which imports them all.

Each half runs on its own JavaScript engine:

- **The [main thread](/guide/glossary.md#main-thread)** runs PrimJS, a QuickJS-based engine, and its code ships as bytecode. Older Lynx code calls this runtime **Lepus**.
- **The [background thread](/guide/glossary.md#background-thread)** runs PrimJS on Android and JavaScriptCore on iOS.
- **On the web**, `@lynx-js/web-core` runs the main thread in an iframe and the background thread in a Web Worker.

## Angular boots on the main thread

`bootstrapApplication()` from `@blotch/angular-lynx` starts Angular on the main thread. The background half doesn't call it (see [Threads](/guide/concepts/threads.md) for what this means for app code):

```mermaid
sequenceDiagram
    participant N as Lynx engine
    participant M as Main thread
    participant B as Background thread
    B->>B: modules run, bridges listen<br/>bootstrapApplication() returns
    N->>M: renderPage()
    M->>M: bootstrapApplication()<br/>LynxDocument
    M->>N: __CreatePage, __CreateView, __AppendElement…
    M->>M: markFirstRenderComplete()
    N->>N: flush after renderPage returns
```

- **The main thread** waits for the engine to call the global `renderPage()`, then bootstraps with a `LynxDocument`.
- **The background thread** doesn't load the app. Angular and your components aren't in its half of the bundle. That half starts from an entry the build plugin generates, which loads:
  - the runtime, whose bridges start listening
  - each file that calls `backgroundFn()`, `createMainThreadRef()` or `new MainThreadRef()` at module level, so each function registers
- **Before a module runs**, on both threads, the build has it import the built-in methods it calls that the engine lacks. That covers up to ES2026, such as `.at()` and `toSorted()` ([JavaScript language level](/guide/concepts/javascript-environment.md#javascript-language-level)).
- **Before either**, the runtime installs its globals: `onerror` handlers that forward to `_ReportError`, polyfills (timers from `lynx.setTimeout`, `URL`, `queueMicrotask`), and the registry for [main-thread scripts](/guide/glossary.md#main-thread-script).

**`LynxDocument`** creates real native elements through Lynx's element functions (`__CreateView`, `__SetAttribute`, …).

Earlier versions booted a second copy of the app on the background thread, on an in-memory document. Nothing read its elements, but its constructors, `ngOnInit` hooks and effects ran, so shared side effects happened twice.

## Reaching the background thread

The background thread has APIs the main thread lacks, such as `fetch`, `NativeModules`, `lynx.getJSModule()` and `lynx.requestResourcePrefetch()`. The main thread reaches them with Lynx's event channels: it dispatches on `lynx.getJSContext()`, and the background thread replies on `lynx.getCoreContext()`.

- **`backgroundFn()` and `runOnBackground()`** call your own functions.
- **`callOnBackground()`** (`background-call.ts`) calls the APIs AngularLynx's services use: fonts, accessibility, exposure, session storage, resource prefetching, native modules and JS modules. Function arguments, such as a native module's callback, are sent as markers, and the background thread calls them back on the main thread.
- **The main thread's `fetch` and `XMLHttpRequest`** (`network/`) send each request through `callOnBackground()` to the background thread's `fetch`. Bodies cross as text, or as base64 when they're bytes, and an `AbortSignal` aborts the background request too. `HttpClient` uses them like the browser's.
- **`LynxLogger`** relays log entries to a listener that posts them to the dev server.

The background thread finds a function by ID, so both threads must give it the same one. The build plugin gives each module-level `backgroundFn()` and `MainThreadRef` an ID from its file and position (`cross-thread-transform.ts`).

The plugin finds those files and writes the background entry to import them (`background-entry.ts`). It looks in Angular's compiled output, and in installed packages that depend on `@blotch/angular-lynx`.

Each file loads on its own. A file's top-level code, or an import's, can throw on the background thread, for example by calling a main-thread-only element function. The build warns about such a call first (`background-globals.ts`). It looks for the element functions in the top-level code of each module the background thread loads. It leaves out:

- functions that aren't called right where they're defined;
- the branches behind `if (__MAIN_THREAD__)`, and behind a `typeof` check that finds the same function (`typeof __CreateView === 'function'`, but not `=== 'undefined'`);
- AngularLynx's own packages, which check the thread themselves.

A build with Rsbuild's persistent cache (`performance.buildCache`) skips the check, since it doesn't read cached modules again.

If a file throws anyway:

- The runtime logs the file's path and the cause.
- The other files still register their functions.
- A call to one of that file's functions fails with an error that names the file.

A file the main thread loads lazily, such as a lazy route's, loads at startup on the background thread. So its functions are registered before the route opens.

## How Renderer2 maps onto Lynx

`LynxRenderer` implements Angular's `Renderer2`. It delegates to `LynxDocument` and to `LynxElement`, a wrapper around a native element reference:

| `Renderer2` call                | What runs                                                                                                                                                                 |
| ------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `selectRootElement()`           | `__CreatePage` for the root component's selector, or the element `createComponent(…, { hostElement })` is given, emptied (below)                                          |
| `createElement(tag)`            | The tag's creator: `__CreateView`, `__CreateText`, `__CreateImage`, `__CreateScrollView`, …, or `__CreateElement('x-…')` for [XElement](/guide/glossary.md#xelement) tags |
| `createText(value)`             | `__CreateRawText`                                                                                                                                                         |
| `createComment()`               | `__CreateView` with `display: none`                                                                                                                                       |
| `appendChild()`                 | `__AppendElement`                                                                                                                                                         |
| `insertBefore()`                | `__InsertElementBefore`                                                                                                                                                   |
| `removeChild()`                 | Queues the removal. `__RemoveElement` runs at the end of the cycle                                                                                                        |
| `setAttribute()`                | `__SetClasses` for `class`, `__SetInlineStyles` for `style`, `__SetID` for `id`, `__SetDataset` for `data-*`, otherwise `__SetAttribute`                                  |
| `setStyle()`, `removeStyle()`   | `__AddInlineStyle` (a `null` value removes)                                                                                                                               |
| `addClass()`, `removeClass()`   | On iOS and Android during change detection, one `__SetClasses` per element at the end of the cycle. Otherwise `__AddClass`; `__GetClasses` then `__SetClasses`            |
| `setValue()` on a text node     | `__SetAttribute(el, 'text', value)`                                                                                                                                       |
| `listen()`                      | `__AddEvent(el, eventType, name, { type: 'worklet', value: listener })`, with `eventType` from the `bind`, `catch`, `capture-` or `global-` prefix                        |
| `parentNode()`, `nextSibling()` | The parent the runtime put the element in, or `__GetParent` for one it didn't (a hydrated element); `__NextElement`                                                       |

A few choices behind the table:

- **Comment anchors are hidden views.** Angular inserts `@if`, `@for` and `createComponent()` content next to comment nodes. Lynx's non-element node crashes the tree functions Angular calls on anchors, so a `display: none` view stands in.
- **A component's host element is emptied, as on the web.** `createComponent(…, { hostElement })` renders into the element it's given, which loses what it held: its children's removals are queued, as `removeChild()`'s are, for the end of the cycle. The element keeps its content when Angular asks it to (hydration, `ShadowDom`), and the page is never emptied.
- **Unknown tags become views.** Component host elements such as `<app-card>` go through `createElement()`, and they need to be real layout boxes.
  - A component that called `registerHostElement()` gets the element it registered instead, such as a `<text>`.
  - `createElement()` only sees the tag, so the registration is keyed by the component's selector.
- **`<list>` is special.** It returns a `LynxListElement`, whose children the engine requests through a `componentAtIndex` callback instead of `__AppendElement`.
- **Native references can't be hashed.** Using one as a `Map`, `Set` or `WeakSet` key crashes the main-thread engine. Wrappers are keyed by `__GetElementUniqueID()` instead.
- **`listen()` adds `stopPropagation()`, `stopImmediatePropagation()` and `preventDefault()`** to event objects, which lack them, so Angular's own listener wrapper doesn't throw.
  - **The propagation methods stop the event from propagating further**, as on the web. On iOS and Android, the element's handler returns Lynx's stop result, which Lynx reads from a main-thread handler. In the web preview, the next element's handler finds the event stopped.
  - **The `preventDefault()` it adds does nothing.** An event with its own, as a pointer event has, keeps it.
  - **Pointer events on iOS and Android** are made by each listening element from its touches, so their `stopPropagation()` reaches no other element (see [Handling taps and events](/guide/elements/event-handling.md#stop-an-event-from-bubbling)).
- **Class changes wait for the end of the cycle on iOS and Android.** Angular applies a `[class]` binding one class at a time. The engine resolves styles only when the tree is flushed. So `end()` writes each changed element's class string in one call.
  - A selector query, an attribute read or an element animation in the meantime writes them first.
  - Some elements get a call for each change, as before: one whose native class list the runtime can't know exactly. Examples are one from a server render's snapshot, or one given a class it has already.
  - So does every change outside change detection.
  - So does Lynx for Web, whose layout and style reads come from the DOM at once.

## Emulated and None renderers

`LynxRendererFactory2.createRenderer()` picks a renderer per component type:

- **`ViewEncapsulation.None`**, or no type: one shared `LynxRenderer`.
- **`ViewEncapsulation.Emulated`**, the default: one `EmulatedLynxRenderer` per component, keyed by its `ɵcmp.id`. It adds a `_ngcontent-<id>` class to every element it creates, and a `_nghost-<id>` class to each host element of the component.
- **`ViewEncapsulation.ShadowDom`**: logs a warning and falls back to `LynxRenderer`.

The browser's emulated renderer adds `_ngcontent-*` and `_nghost-*` attributes. Angular's compiler scopes the component's selectors with them. Lynx's CSS engine can't match attribute selectors, so the build plugin:

- turns them into class selectors
- sets each component's `ɵcmp.id` to the scope ID the CSS was compiled with, made from its class name and file path

Elements keep their scope classes when Angular replaces their whole class list.

**Type selectors get a class too.** Every renderer gives a `_ngtag-<tag>` class to an element whose tag isn't a Lynx element. That's a component's host, or a web tag such as `div`. The build plugin rewrites type selectors naming such tags to it. So `app-card { … }` matches the `<view>` the host renders as.

## The flush cycle

Element functions change the engine's element tree right away. But nothing is laid out or drawn until **`__FlushElementTree()`** runs.

Angular calls `begin()` and `end()` on the renderer factory around every change-detection cycle. `end()` runs, in this order:

1. **`processPendingClasses()`** writes the classes the cycle changed, with one `__SetClasses` per element.
2. **`processPendingRemovals()`** commits queued removals with `__RemoveElement`.
3. **`processPendingTextNormalization()`** trims edge spaces from text runs that changed. A run that's all its `<text>` holds was sent trimmed when it was set, so it skips this.
4. **`processPendingListUpdates()`** tells each `<list>` that gained, lost or moved items which ones, with its `update-list-info`.
5. **`__FlushElementTree()`** commits everything to the screen, the lists' updates included. It's one flush, however many lists changed. The engine asks each list for its items while it lays them out, and each item is flushed on its own as it's added.

:::warning Never flush while a list builds an item

A list builds its items inside the engine's layout. A flush there would re-enter the layout and crash. A `*lynxListFor` item's change detection runs there, so its `end()` updates the lists in the item and leaves the flush to the item.

:::

**The first render isn't flushed by `end()`.** Bootstrap's change detection still runs inside the engine's `renderPage()` call. A promise continuation doesn't escape it, because the engine drains microtasks before the call returns.

- **Until `markFirstRenderComplete()`, `end()` makes no flush.** The engine flushes once `renderPage()` returns.
- **Work that must not run inside that call waits for a `setTimeout`.** `end()` parks the changed lists instead of sending their updates. They're sent then, with one flush.
- **On the web, the runtime schedules a flush.** `@lynx-js/web-core` has no flush after `renderPage()`.

**Changes outside a cycle get a settle flush.** `scheduleSettleFlush()` queues one microtask that commits removals, text, any lists that changed, and a flush. It runs when:

- an element is created outside a cycle, such as a lazy route's component that `RouterOutlet` builds during navigation
- an event handler returns, if something has been written since the last flush. That's an element changed directly without changing a signal, or a change made from a timer or a promise. An event with nothing waiting doesn't flush, so a scroll or a drag doesn't flush on every frame
- a removed element is rebuilt

It's skipped inside a cycle, because `end()` will flush, and during the first render. Main-thread scripts batch their own changes into one flush on a microtask.

## How a tap reaches the screen

Change detection is zoneless (see [Signals and change detection](/guide/concepts/signals.md)). A tap runs like this:

1. The engine calls the global `runWorklet()` on the main thread with the listener that `listen()` registered.
2. The listener runs your handler synchronously, inside the native event.
3. Your handler sets a signal. Angular marks the view dirty, and its zoneless scheduler queues a tick, racing `setTimeout` against `requestAnimationFrame`. Lynx puts its timers on `lynx`, so the runtime copies them onto `globalThis` at startup.
4. When the handler returns, `scheduleSettleFlush()` queues a microtask if the handler changed elements directly. A handler that only sets signals leaves the flush to the tick.
5. The tick runs change detection. The renderer calls element functions, and `end()` flushes.

Changing the tree in step 2 is safe, though the engine is still delivering the event: a handler can create and remove elements, and even flush them with `ApplicationRef.tick()`. A navigation changes it later anyway, since the router builds the next screen after the handler returns.

## Removal, moves and rebuilding

Angular moves a view by removing it and inserting it again in the same tick. `remove()` only queues the element, so an insert in the same tick cancels the removal. The engine sees a move, and the native element keeps its subtree.

A removal that isn't undone before the flush destroys the element's native view, and Lynx can't bring it back.

So every `LynxElement` caches what was set on it: attributes, id, dataset, classes, styles, listeners, text and children. Inserting a destroyed element rebuilds it, and its subtree, from that cache. This is how content shown again by an `@if`, or a route you return to, still renders.

## Text inheritance

Lynx doesn't pass text styles down, so HTML text tags and loose text get them through CSS variables, which it does pass down. It works in three steps.

### 1. The build copies text styles to variables

The build copies each inheritable declaration in your CSS to a variable of its own. `color: red` also sets `--angular-lynx-color: red`.

- **The copies are narrowed to the class `_nginherit`.** The runtime gives that class to each element with such text inside, and to its ancestors.
- **Only those elements get it.** An element that sets custom properties costs Lynx a copy of the whole set, so the others don't get the class.
- **The copies of a rule naming `text` are narrowed to `_nginherit-text` instead**, such as the theme's `view > text`. Only a Lynx `<text>` gets that class, so the copies skip an HTML text tag. On the web, no `text` rule matches a `<p>`.
- **Inline styles are copied by the runtime.** The build sees only stylesheets. So the runtime copies an inline `style` or `[style.x]` text style to the same variable itself. It goes in the element's inline style, ahead of the app's own declarations.

### 2. The runtime reads them where no rule applies

Each HTML text tag then reads `var(--angular-lynx-<property>)` in its inline style for each property its own rules don't set.

- The build plugin gives the runtime an index of the app's rules. For each selector, it records what the selector requires of the element and its ancestors.
- The runtime matches that index against the element tree.
- It works the answer out again when an ancestor's classes change, if a rule needs one of the changed classes.

### 3. Selectors reach through anonymous text

Loose text and the inline tags beside it are drawn in an anonymous `<text>` (class `_ngtext`). On Lynx, that `<text>` is the tags' parent.

- **The build adds a second selector through it** for a child combinator in front of what may be an inline tag. `.row > b` also matches as `.row > ._ngtext > b`.
- **The runtime's matching walks up through the anonymous `<text>` too.** So it agrees with Lynx's on which rules apply.

## Route views

`provideRouter()` keeps Angular's own route reuse strategy, so leaving a route destroys its components, as on the web.

It used to install `LynxRouteReuseStrategy`, which keeps every route's view alive. An early crash investigation had blamed a native element pool of about 256 slots that removing an element never freed.

**There's no such limit.** Measured on Lynx 4.1 in the iOS Simulator and an Android emulator, 400 navigations between two pages of 300 elements created over 121,000 native elements. Nothing crashed.

The strategy saved none of them, because a reattached route rebuilds its elements from cache (see above). It's still exported, for apps that want route state to survive navigation.

## Routing without a browser

`provideRouter()` from `@blotch/angular-lynx` wraps Angular's and swaps two providers:

- **`LynxPlatformLocation`** replaces `BrowserPlatformLocation`, which reads `window.location` and crashes on Lynx. It keeps location state in memory, parses URL strings by hand, and reports `href` as `lynx://app/…`. It needs its own `@Injectable()`: without one, Angular inherits `PlatformLocation`'s factory and builds the browser class.
- **`LynxLocationStrategy`** replaces `PathLocationStrategy`. It keeps a history stack and an index in memory. `back()` and `forward()` move the index and notify `popstate` listeners.

**Failed navigations resolve.** It sets `resolveNavigationPromiseOnError: true`, so a failed navigation resolves to `false` instead of rejecting. Unhandled rejections there used to leave a blank screen. Listen for `NavigationError` to see failures.

**`URL` is polyfilled.** The main thread has no `URL` class, and since Angular 22.2 the router's URL serializer calls `new URL()`. Without it, every URL serialized to `/` and no navigation happened. The runtime installs a `URL` and `URLSearchParams` polyfill that follows the web's URL Standard.

## Related

- [Threads: where your code runs](/guide/concepts/threads.md)
- [Signals and change detection](/guide/concepts/signals.md)
- [Routing and navigation](/guide/routing/index.md)
- [Main-thread scripts](/guide/main-thread/index.md)
- [`@blotch/angular-lynx-build` reference](/api/build/index.md)
