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

# LynxNativeModule

Call native code that the host app exposes, and share JavaScript modules within a page. `import { LynxNativeModule, type NativeModuleMap, type NativeModuleProxy } from '@blotch/angular-lynx';`

A **native module** is an object that the [host app](/guide/glossary.md#host-app) registers, with methods written in Swift, Kotlin or another native language. The host app is the native iOS or Android app that runs your bundle.

## Usage

```typescript title="src/app/home.ts"
import { Component, inject } from '@angular/core';
import { LYNX_ELEMENTS, LynxNativeModule } from '@blotch/angular-lynx';

@Component({
  selector: 'app-home',
  imports: [LYNX_ELEMENTS],
  template: `<text>Home</text>`,
})
export class Home {
  readonly #native = inject(LynxNativeModule);

  constructor() {
    // Tell the host app that this screen opened.
    void this.#native.call('trackScreen', { name: 'home' });
  }
}
```

## API

### `LynxNativeModule`

```typescript
@Injectable({ providedIn: 'root' })
class LynxNativeModule {}
```

Typed access to Lynx's native module bridge and its JavaScript module registry. Every method is safe to call outside Lynx: it does nothing, or returns `undefined`.

:::info Calls run on the background thread
Lynx provides native modules and the module registry only on the [background thread](/guide/glossary.md#background-thread), and your app runs on the main thread. So every method sends its call there for you:

- **Results are copied as JSON**, and arrive as a promise.
- **Callbacks you pass,** such as a listener or a native method's callback, are called back on the main thread with their arguments copied as JSON. Setting a signal in one updates the screen.
- **A listener you remove is let go.** This holds for a function you pass only to a module's `addListener()`, such as `GlobalEventEmitter`'s. Each `addListener(event, listener)` counts once, on every event. Once `removeListener(event, listener)` or `removeAllListeners()` has removed them all, the main thread forgets the listener. Then it, and what it holds, can be garbage collected, and an event already on its way doesn't call it.
- **Every other function you pass is kept while the page is open,** since the host can call it at any time. That covers a native method's callback, `on()`'s callback and a registered module's methods. A listener you've also passed one of those ways is kept too.
- **A module is a stand-in.** `getNativeModule()` and `getJSModule()` return an object whose methods each run on the background thread and return a promise of the result.

See [Threads](/guide/concepts/threads.md).
:::

### `LynxNativeModule.call()`

```typescript
call<T = unknown>(name: string, params?: Record<string, unknown>): Promise<T | undefined>;
```

Calls the host's bridge method `name` with `params`, which defaults to `{}`. Resolves with the first value the host passes back, or `undefined` when there is no bridge.

### `LynxNativeModule.on()`

```typescript
on(name: string, callback: (...args: unknown[]) => void): void;
```

Listens for the bridge event `name` from the host. `callback` gets the event's arguments, copied as JSON. There's no way to stop listening.

### `LynxNativeModule.getNativeModule()`

```typescript
getNativeModule<K extends string>(
  name: K,
): K extends keyof NativeModuleMap
  ? NativeModuleProxy<NativeModuleMap[K]> | undefined
  : unknown;
```

Returns a stand-in for the native module the host registered as `name`, or `undefined` outside Lynx. Each method you call on it runs on the background thread and returns a promise of the method's return value. The promise rejects if the host has no such module or method.

For a module you've added to [`NativeModuleMap`](#nativemodulemap), the return type is a [`NativeModuleProxy`](#nativemoduleproxy) of it. For any other name it's `unknown`.

### `LynxNativeModule.getJSModule()`

```typescript
getJSModule<T = unknown>(name: string): T | undefined;
```

Returns a stand-in for a JavaScript module registered in this page, such as Lynx's `GlobalEventEmitter` or one from `registerJSModule()`, or `undefined` outside Lynx. Like `getNativeModule()`, its methods return promises, and reject if the module isn't registered.

### `LynxNativeModule.registerJSModule()`

```typescript
registerJSModule<T extends object>(name: string, module: T): void;
```

Registers `module` under `name`, so other code in this page, including native callbacks, can find it.

The background thread registers a copy:

- **Its methods,** including ones on `module`'s class, call yours on the main thread with their arguments copied as JSON. Their return values are dropped.
- **Its other fields** are copied once.

## Types

### `NativeModuleMap`

```typescript
interface NativeModuleMap {}
```

Maps module names to their types for `getNativeModule()`. It's empty until you add your host's modules to it with [module augmentation](https://www.typescriptlang.org/docs/handbook/declaration-merging.html#module-augmentation). Write each method as the host implements it, returning what the native method returns:

```typescript title="src/native-modules.d.ts"
// This export makes the file a module, so the block below adds to
// @blotch/angular-lynx's types instead of replacing them.
export {};

declare module '@blotch/angular-lynx' {
  interface NativeModuleMap {
    DeviceModule: {
      getBatteryLevel(): number;
      vibrate(durationMs: number): void;
    };
  }
}
```

Then `getNativeModule('DeviceModule')` is typed, with no casting:

```typescript title="src/app/battery.ts"
import { Service, inject } from '@angular/core';
import { LynxNativeModule } from '@blotch/angular-lynx';

@Service()
export class Battery {
  readonly #device = inject(LynxNativeModule).getNativeModule('DeviceModule');

  // Promise<number | undefined>: the call runs on the background thread.
  async read(): Promise<number | undefined> {
    return this.#device?.getBatteryLevel();
  }
}
```

### `NativeModuleProxy`

```typescript
type NativeModuleProxy<T> = {
  [
    K in keyof T as T[K] extends (...args: any[]) => unknown ? K : never
  ]: T[K] extends (...args: infer A) => infer R
    ? (...args: A) => Promise<Awaited<R>>
    : never;
};
```

A native module as `getNativeModule()` returns it. Native modules exist only on the background thread, so each method call is sent there.

- **Each method** takes the same arguments and returns a promise of the method's result, copied as JSON.
- **Callbacks you pass** are called back on the main thread.
- **Only methods are on it.** Other properties of the module aren't reachable.

## Related

- [Embed in an existing native app](/guide/embedding/index.md)
- [Pass data from your native app](/guide/embedding/host-data.md)
- [Lynx native modules docs](https://lynxjs.org/guide/use-native-modules.html)
