# Getting started Angular Native is in alpha. Every effort has gone into making it stable and accurate, but you may still hit bugs. If you do, please [open an issue](https://github.com/ng-native/ng-native/issues/new/choose). ## Create the app ```sh npx create-expo-app@latest my-app --template @ng-native/template cd my-app npx expo start ``` `create-expo-app` installs the template's framework packages and Angular, with the Metro preset configured in `metro.config.js`. No manual installation is needed. For an existing Expo app, see [Adding it to an existing app](/guide/manual-setup). In an Angular CLI or Nx workspace, add the same app as a project with `ng add @ng-native/schematics` (see [Angular CLI](/packages/schematics)), or `nx add @ng-native/nx` then `nx g @ng-native/nx:app apps/mobile` (see [Nx](/packages/nx)). Scan the QR code with [Expo Go](https://expo.dev/go), or press `i` or `a` for a simulator. The Angular component renders native views: `` becomes a `UIView` on iOS or an `android.view.View` on Android, with a press handler and no React in the render path. Before each release, checks publish every package to a registry, generate a template app with the command above, install dependencies by version, typecheck, test and bundle it. Any failure blocks the release. ## Edit `app.ts` and check the counter Import each element as an Angular component and use lowercase names. The template generates this `src/app/app.ts`: ```ts import { Component, inject, signal } from '@angular/core'; import { Pressable, SafeAreaProvider, SafeAreaView, Text, View } from '@ng-native/components'; import { StatusBar } from '@ng-native/device'; /** * Element names are lowercase, and that is load-bearing rather than style: an uppercase name such * as matches no component's selector, and the Metro transform fails the build on it. */ @Component({ imports: [Pressable, SafeAreaProvider, SafeAreaView, Text, View], selector: 'app-root', template: ` Angular, natively Real native views. React is never in the render path. Tapped {{ count() }} times `, styles: ` :host { flex: 1; } .screen { flex: 1; background-color: #f5f5f7; } .body { flex: 1; justify-content: center; gap: 12px; padding: 24px; } .title { color: #101014; font-size: 28px; font-weight: 700; } .hint { color: #5f5f6b; font-size: 15px; } .button { align-items: center; margin-top: 8px; padding: 14px; border-radius: 10px; background-color: #3b6ef5; } .label { color: #ffffff; font-size: 16px; font-weight: 600; } @media (prefers-color-scheme: dark) { .screen { background-color: #101014; } .title { color: #ffffff; } .hint { color: #8b8b96; } } `, }) export class App { protected readonly count = signal(0); constructor() { // Dark status bar icons in light mode and light ones in dark mode. Unclaimed, Android keeps // light icons whatever the scheme. inject(StatusBar).set({ style: 'auto' }); } } ``` Edit the `title` text and save to see it update on the device. Press the button to increment `count`: its label reads "Tapped 1 times", "Tapped 2 times", and so on. Use lowercase names such as `` and ``. An uppercase name such as `` matches no component's selector, and the Metro transform fails the build on it. An element used without its import renders a plain view and logs a development warning. ## Run `app.test.ts` ```sh npm test ``` `app.test.ts` checks that pressing the button increments the counter. It runs in Node in well under a second, without a simulator, rendering against a fake native host and querying what native would receive. ```ts import { render, screen, userEvent } from '@ng-native/testing'; import { expect, test } from 'vitest'; import { App } from './app.ts'; test('counts taps', async () => { await render(App); await userEvent.setup().press(screen.getByRole('button', { name: 'Tapped 0 times' })); expect(screen.getByText('Tapped 1 times')).toBeTruthy(); }); ``` `app.device.ts` beside it runs inside the app instead, on a simulator or emulator's real native views. `npx vitest --project ios` (or `--project android`) starts Metro, builds the app, opens it and runs the test. The first run takes some minutes and needs Xcode or the Android SDK; see [Tests inside the running app](/packages/testing/in-app-tests). [Testing](/packages/testing) explains what these tests prove and their limits. [Writing a test](/packages/testing/writing-a-test) covers forms, services and routing. ## Style a control `` handles presses without built-in styling; there is no styled component library to adopt. Bind Tailwind classes to state after [setting up Tailwind](/packages/tailwind): ```ts import { Component, signal } from '@angular/core'; import { Pressable, Text } from '@ng-native/components'; @Component({ selector: 'app-root', imports: [Pressable, Text], template: ` Wi-Fi `, }) export class App { protected readonly wifi = signal(true); } ``` [Theming and Tailwind](/guide/theming) covers what a class string means on a platform with no browser. ## Update templates and styles Template and stylesheet edits preserve component state through Angular's `ɵɵreplaceMetadata`, which the Metro transform embeds in the module. No Angular dev server is involved. An edited method or function is patched onto the running app as well. An edit that cannot be, to a field, a constructor or a constant, reloads the app and returns to the page it left; the console logs why. [Limitations](/guide/limitations) lists each case. ## Expo Go or a development build `npx expo start` supports both. Expo Go covers most development. For a native module or dependency patch absent from Expo Go, create a development build with `npx expo run:ios`, `npx expo run:android` or EAS. For distribution, create a release build. Scanning the `expo start` QR code opens Expo Go on a physical device; `--dev-client` opens an installed development build. ## Building for release `npx expo run:ios --configuration Release` and `npx expo run:android --variant release` build standalone apps. [EAS Build](https://docs.expo.dev/build/introduction/) (`eas build`) builds on Expo's machines. Follow Expo's instructions for configuration and signing. The Metro preset sets Angular's production mode, replacing `ngDevMode` with `false` when `__DEV__` is false to remove dev-mode assertions and performance counters. See [Metro](/packages/metro). ## Where to go next [Theming and Tailwind](/guide/theming) covers styling, [Screens and navigation](/packages/router/screens) adds screens, and [Writing a test](/packages/testing/writing-a-test) extends the template's test. [Components](/packages/components) lists the available elements. For manual setup in an existing Expo project, see [Adding it to an existing app](/guide/manual-setup). Read [Architecture](/guide/architecture) to understand how Angular drives native views, [Known limitations](/guide/limitations) for alpha gaps, and [Angular Native compared](/guide/comparison) for comparisons with React Native, NativeScript, Ionic and Flutter. --- # Adding it to an existing app The [Getting started](/guide/getting-started) template is the shorter route, verified end to end before each release. For manual setup in a blank or existing Expo app, complete every step below. Each step includes troubleshooting notes. Angular CLI and Nx generators perform this setup and integrate workspace commands: use `ng add @ng-native/schematics` ([Angular CLI](/packages/schematics)) or `nx g @ng-native/nx:app` ([Nx](/packages/nx)). ## Start the project **Create a blank project:** ```sh npx create-expo-app my-app --template blank-typescript@sdk-58 cd my-app rm App.tsx index.ts npm pkg set main=src/main.ts ``` The packages support Expo SDK 57 and 58. `@sdk-58` starts the app on SDK 58, the SDK the template is on; without it, `create-expo-app` takes the newest SDK. **For an existing app:** it has to be on SDK 57 or 58. An app on an older SDK moves with `npx expo install expo@^58.0.0`, then `npx expo install --fix`. Remove its entry point, `App.tsx` and `index.ts` or `index.js`, and run `npm pkg set main=src/main.ts`, so Expo starts from the `src/main.ts` below. Keep the dependencies, native configuration and assets. For either route, install the framework, configure Metro and write the two app files below. ## Install the framework packages ```sh npm install @angular/core @angular/common \ @ng-native/platform @ng-native/fabric \ @ng-native/components @ng-native/device @ng-native/metro ``` `` and `` use `react-native-safe-area-context` native views. Install it if you use them, as most apps do to clear the notch: ```sh npx expo install react-native-safe-area-context ``` Expo Go bundles it, hiding a missing installation until a development or release build renders `Unimplemented component: `. Add `@ng-native/router`, `@ng-native/expo` and `@ng-native/icons` as needed. Expo modules are optional peers, so `@ng-native/expo` installs no native code. Install individual modules such as `expo-haptics` for the capabilities you need. ## Configure Metro ```js // metro.config.js const { getDefaultConfig } = require('expo/metro-config'); const { withAngularNative } = require('@ng-native/metro/config.cjs'); module.exports = withAngularNative(getDefaultConfig(__dirname)); ``` `withAngularNative` registers Angular's ahead-of-time transformer, compiles component CSS into engine sheets, and adds source extensions to invalidate external templates. It installs `ngDevMode` and `animate.enter`/`animate.leave` polyfills before `@angular/core` loads. Pass `{ workspaceRoot }` in a monorepo where framework packages sit outside the app's `node_modules`. Add the package's config plugin to `app.json` as well: ```json { "expo": { "plugins": ["@ng-native/metro"] } } ``` An app built with the iOS 27 SDK has to adopt the UIKit scene life cycle or it exits at launch, and the `AppDelegate.swift` that `expo prebuild` writes does not. The plugin starts React Native from a scene delegate instead, passing on the links the app is opened with, and answers the status bar from view controllers, which is the only way that SDK still lets an app change it. On Android the plugin changes nothing unless asked. React Native ships layout animations off there, so [`LayoutAnimation`](/packages/device/layout-animation) makes its change without animating it; passing `["@ng-native/metro", { "android": { "layoutAnimations": true } }]` turns them on in the `MainApplication.kt` that `expo prebuild` writes. ## Configure TypeScript ```json // tsconfig.json { "extends": "expo/tsconfig.base.json", "compilerOptions": { "strict": true, "allowImportingTsExtensions": true } } ``` `allowImportingTsExtensions` is required. These packages ship TypeScript with `.ts` imports so Metro's Angular compiler processes library and app components together. Without this setting, `tsc` reports errors for files in `node_modules`. `extends` names Expo's file with its `.json`. From SDK 58 `expo` has an exports map, and Vitest cannot find `expo/tsconfig.base` without the extension: every test file fails to load with `Failed to load tsconfig 'expo/tsconfig.base'`. `tsc` accepts either name. ### Checking templates `tsc` checks TypeScript only: a template that binds an input a component does not have, such as `` where the input is `checked`, compiles, bundles and does nothing. Angular's own compiler checks templates. With `@angular/compiler-cli` installed as a development dependency, add its options to the same `tsconfig.json` and type-check with `ngc` instead of `tsc`: ```json { "angularCompilerOptions": { "strictTemplates": true, "typeCheckHostBindings": false, "strictDomEventTypes": false } } ``` ```sh ngc -p tsconfig.json --noEmit ``` `typeCheckHostBindings` is off because the components' own host bindings name native props that Angular's DOM schema does not know. `strictDomEventTypes` is off because a native event such as `(scroll)` is an element event, not an output, so under the DOM schema its `$event` would be typed as a DOM `Event`. A view registered by name, such as `registerExpoView('expo-image', 'ExpoImage')`, is used through a component whose inputs are its props, so the template is checked against them: `@ng-native/expo` has one for each view `registerExpoViews` knows, such as `ExpoImage`, `ExpoVideo` and `Camera`, and the `Ui*` SwiftUI components, and a view with none yet gets a small one of the same shape. Leave `CUSTOM_ELEMENTS_SCHEMA` and `NO_ERRORS_SCHEMA` out: either turns template checking off for the whole component. ## Write the entry point ```ts // src/main.ts // Expo's runtime: its fetch, whose response streams a body, and URL, TextDecoderStream and // structuredClone. Metro runs it before this file only when something imports it, and nothing // else does in a release build, which would then get React Native's fetch, with no body. import 'expo'; import { AppRegistry, Image, Platform, processColor } from 'react-native'; import { mount } from '@ng-native/platform'; import { currentConditions, deviceTokens, watchConditions } from '@ng-native/device'; import { getFabricUIManager, registerPlatformComponents } from '@ng-native/fabric'; import { App } from './app/app.ts'; registerPlatformComponents(Platform.OS); AppRegistry.registerRunnable('main', ({ rootTag }) => { const app = mount(Number(rootTag), App, getFabricUIManager(), { processColor, conditions: currentConditions(), tokens: deviceTokens(), resolveAssetSource: (value) => Image.resolveAssetSource(value as never), }); const stopWatching = watchConditions(app.engine); app.applicationRef.onDestroy(stopWatching); }); ``` The entry point configures colors, assets and device-dependent styles before rendering: - **`conditions`** supplies `@media` values. `watchConditions` updates them on rotation or theme changes, making `dark:` follow the system. It returns a function that stops it, called as the app is destroyed: Android destroys the app when it recreates the activity, after mounting a new one. - **`tokens`** supplies device values such as hairline width. Without it, `1px` produces a thick divider instead of a third of a point on a 3x screen. - **`resolveAssetSource`** converts `require('./x.png')` to a native-loadable asset; without it, images stay blank. - **`processColor`** converts colors to platform integers. ## Write the root component ```ts // src/app/app.ts import { Component, signal } from '@angular/core'; import { Pressable, Text, View } from '@ng-native/components'; @Component({ imports: [Pressable, Text, View], selector: 'app-root', template: ` tapped {{ count() }} times tap me `, styles: ` .box { flex: 1; justify-content: center; padding: 24px; } `, }) export class App { protected readonly count = signal(0); protected bump(): void { this.count.update((n) => n + 1); } } ``` Import each element's component, for example `imports: [View, Text]`. Missing imports render plain views and trigger development warnings. Use lowercase element names. An uppercase name such as `` matches no component's selector; the Metro transform fails the build on it. Run `npx expo start`, then scan the QR code with Expo Go or press `i` or `a` for a simulator. Check that each press increments the counter. ## Add Tailwind Skip Tailwind if you use plain `[style]` objects. ```sh npm install @ng-native/tailwind tailwindcss @tailwindcss/cli ``` ```css /* src/styles.css */ @import 'tailwindcss/theme.css'; @import 'tailwindcss/utilities.css'; @import '@ng-native/tailwind/native.css'; ``` ```js // metro.config.js const { withTailwind } = require('@ng-native/tailwind/config.cjs'); module.exports = withTailwind(withAngularNative(getDefaultConfig(__dirname)), { input: './src/styles.css', }); ``` ```ts // src/main.ts import tailwind from '../.angular-native/app.tailwind.js'; // ...and in the mount options, beside processColor: globalStyles: tailwind, ``` Expo's transform worker returns empty native modules for `.css` files, so the generated sheet uses `.js`. `withTailwind` runs and watches the Tailwind CLI, updating the sheet when template classes change without restarting. Metro generates the sheet and its `.d.ts` in `.angular-native/` on startup. Start Metro before the first typecheck, and add `.angular-native/` to `.gitignore` since it is rebuilt on every start. See [Theming and Tailwind](/guide/theming) for how classes work without a browser. ## The dev loop Template and style edits hot-swap on the device, preserving component state, and an edited method or function is patched onto the running app. An edit to a field, a constructor, a constant or a selector reloads the app and returns to the page it left; the console logs why. ## Where to go next Continue with [Build a form](/guide/forms), [Working offline](/guide/offline), then [Deployment](/guide/deployment). --- # Angular Native compared React Native, NativeScript, Ionic and Flutter offer different rendering models, languages, ecosystems and styling systems. The comparisons below include no benchmarks or speed claims. ## React Native Angular Native uses React Native's Fabric renderer and Expo, replacing React, JSX, hooks and the reconciler. Angular's `Renderer2` calls build `@ng-native/fabric`'s retained tree, which commits like React Native's `ReactFabric`; see [Architecture](/guide/architecture). A `` and React Native's `` become identical `UIView`s through the same C++ renderer. `@ng-native/expo` wraps Expo modules as injectable services. `registerExpoView(elementName, moduleName)` registers any Expo module's native view; see [Using a module](/packages/expo/using-a-module). Expo's native implementation works unchanged, regardless of the JavaScript renderer. On the JavaScript side, templates replace JSX, signals replace hooks and `useState`, and dependency injection replaces context and prop drilling. Zoneless change detection replaces re-renders on every state update. `@ng-native/platform`'s `mount()` always enables zoneless mode, with no option to add zone.js; see [Bootstrapping](/packages/platform/bootstrapping). ## NativeScript NativeScript generates synchronous JavaScript bindings for 100% of platform APIs at compile time, including marshalling of all data types ([NativeScript iOS Marshalling docs](https://docs.nativescript.org/guide/ios-marshalling)). It calls Objective-C and Java APIs directly, without React Native or per-API wrappers. Angular Native reuses the RN/Expo module ecosystem, and reaches an SDK no module wraps through [`@ng-native/nativescript`](/packages/nativescript), which embeds that same runtime: every iOS and Android API is callable from TypeScript, and a native view built in TypeScript, a UIView or an Android `View`, can be placed in a template. `@nativescript/angular` is actively maintained: the [NativeScript/angular monorepo](https://github.com/NativeScript/angular) tracks current Angular releases, including 22.0.0 (August 2026) for Angular 22. Its CSS engine emulates text-property inheritance, solving the same problem as [CSS on native](/packages/fabric/css-engine). NativeScript targets iOS, Android and visionOS, with no browser counterpart to [`@ng-native/web`](/packages/web). ## Ionic and Capacitor A Capacitor app runs in the platform's WebView: `WKWebView` on iOS, `android.webkit.WebView` on Android. A JavaScript bridge exposes native plugin methods on `window.Capacitor` ([How Capacitor works](https://ionic.io/blog/how-capacitor-works-2)). Its `ion-button` and `ion-list` web components render as DOM, styled with CSS and shadow DOM. Angular is one of Ionic's three first-class framework targets, with an official, mature integration. Angular knowledge carries over, but `ion-*` components, browser CSS and DOM API calls do not. Angular Native's `` and `` render as `UIView`s and Android `View`s; see [Architecture](/guide/architecture). Ionic is closer to Angular Native's web target: `@ng-native/web` runs in a browser, and both are accessible by URL. Capacitor's UI always runs in a WebView. `@ng-native/web`'s `BrowserEngine` instead implements the same interface as Fabric; see [Native and web](/guide/native-and-web). A component rendered as DOM on this site renders as a `UIView` on a device. ## Flutter Flutter bypasses system UI widgets and paints its own onto a surface through Skia or Impeller. Impeller is the default on iOS and Android (API 29+) from release 3.27 ([Impeller docs](https://docs.flutter.dev/perf/impeller)). It creates no `UIView`s or Android `View`s. This allows pixel-identical rendering across platforms, with its own animation and layout systems. Flutter reimplements controls and their look-and-feel updates, and exposes accessibility through its semantics tree rather than native views. Angular Native's `` uses the platform's switch control and current OS styling. Flutter uses Dart, `pub.dev` and its own build system; it shares no Angular code or npm packages with Angular Native. ## Styling React Native has no CSS engine; NativeWind compiles Tailwind into style objects. Ionic uses DOM CSS, while Flutter styles widgets without a cascade. Angular Native compiles component `styles` with lightningcss and uses `@ng-native/fabric` for runtime matching, inheritance and resolution; see [CSS on native](/packages/fabric/css-engine). `@ng-native/tailwind` uses this cascade, so `class="flex-1 bg-blue-500 p-4"` on a `` matches directly, without an interop layer. ## Maturity Angular Native is an alpha. It implements a retained tree with incremental commits, routing, Signal Forms, CSS, Expo and React Native facades, and Reanimated worklet animations. Release builds (`expo run:ios --configuration Release` / `expo run:android --variant release`) run on the iOS simulator and Android emulator, producing Hermes bytecode with no Angular compiler and `ngDevMode` false. Many platform facades have unit tests and typechecks but no hardware verification. Simulator checks also cover CSS behavior beyond unit tests; see the canary's verify screen and [CSS on native](/packages/fabric/css-engine). Treat this as a working prototype. See [Known limitations](/guide/limitations) for specific gaps. ## When to choose which - Choose Angular Native for an existing Angular app or a team wanting Angular templates, signals and DI with native views and Expo modules. - Choose React Native for a team invested in React, where Fabric's ecosystem is largest. - Choose NativeScript for an app built entirely on direct native SDK access, when that matters more than React Native plugin reuse. - Choose Ionic for a web app that needs installation, or a web team avoiding native build tooling. - Choose Flutter when pixel-identical rendering matters more than native controls, or a new team has no investment in web, Angular or React ecosystems. --- # Theming and Tailwind React Native has no CSS engine: NativeWind compiles Tailwind into style objects, attaches them through `cssInterop` and provides a variant runtime because native views do not understand `className`. Angular Native's cascade already supports selectors, specificity, inheritance, media queries and custom properties. `` matches through `class`, without an interop layer or `className` prop. A build step converts web CSS to the native subset; a preset adds native-specific vocabulary. ## The build step ```css @import 'tailwindcss/theme.css'; @import 'tailwindcss/utilities.css'; @import '@ng-native/tailwind/native.css'; ``` Import `theme.css` and `utilities.css` instead of `tailwindcss` to exclude preflight's browser reset (`html`, `::before`, `-webkit-*`). This documentation site imports preflight explicitly, since its own chrome is a real document even though the components in it are not. The compiler unwraps `@layer` and `@supports`, drops `@property`, substitutes static theme variables, and folds `calc()` through lightningcss. A theme variable the app sets itself stays a `var()` instead (see [Tokens cross component boundaries](#tokens-cross-component-boundaries)). For example, `calc(var(--spacing) * 4)` is constant but cannot resolve on a device. The compiler converts `oklch()` to sRGB as in component stylesheets. Then the utilities compile: ``` p-4 -> { paddingTop: 16, paddingRight: 16, paddingBottom: 16, paddingLeft: 16 } gap-2 -> { gap: 8 } h-16 -> { height: 64 } rounded-lg -> { borderTopLeftRadius: 8, ... } bg-blue-500 -> { backgroundColor: 'rgb(43, 127, 255)' } ``` Unsupported styles produce diagnostics that name the rule's selector, which is what to search the app for: ``` [angular-native] .appearance-none (Tailwind): dropped 'appearance': 'appearance' has no React Native equivalent: no style prop of a native view does what it does. ``` Diagnostics prevent unsupported styles from silently doing nothing. ## The preset `@ng-native/tailwind` contains three files: `shared.css` for platform-independent styles, plus `native.css` and `web.css`, which import it and define four platform-dependent variants. ### `hover:` is the pressed state `:hover` is permanently unsupported by the native matcher and dropped with a build warning. The `hover:` variant instead matches `:active`, which the engine sets on touched views and their ancestors, letting hover classes express touch engagement. `data-hover` is for a trackpad, a mouse or a pencil, through React Native's W3C pointer events, which are off until an app [turns them on](/packages/platform/renderer#pointer-events). Components must listen for these events and set the attribute themselves. Without a pointer the variant remains a press state. ```css /* native.css */ @custom-variant hover (&:active, &[data-hover]); /* web.css */ @custom-variant hover (&:hover, &:active, &[data-hover]); ``` The browser variant includes `:active` for touchscreen laptops and phone browsers, where `:hover` may never fire or may stick after a tap. Use `press:` and `hovered:` to distinguish the states. ### `focus-visible:` is `focus:` on native The web distinguishes keyboard focus from clicks to avoid unnecessary rings. On phones, focus comes from keyboards, remotes or assistive technology, where rings are useful. Since `:focus-visible` is also dropped with a build warning, the native variant aliases it to focus. Both platforms also match `data-focus` so a wrapper can show its control's focus ring. The native text field receives focus, while its wrapper owns the border, radius and padding; the control's composed behavior informs the wrapper. ### `ios:`, `android:`, `web:`, `native:` `mount` adds `platform-ios`, `platform-android` or `platform-web` to the root, enabling Tailwind's platform variants. Variants for absent classes compile but never match, so shared classes such as `ios:pt-2` are harmless on the web. ### `dark:` follows a class Tailwind's default `dark:` uses `@media (prefers-color-scheme: dark)`, which the engine tracks. A class also supports palettes such as `.dark { --background: ... }` and in-app overrides of the OS theme. `watchConditions(app.engine)` keeps the root's `dark` class in sync with the system. For an app switcher, call `watchConditions(app.engine, { darkClass: false })` and control the class yourself; otherwise a system-dark root overrides the switcher's light choice. ```html … ``` ```ts import { computed, inject, signal, Service } from '@angular/core'; import { ColorScheme } from '@ng-native/device'; type Preference = 'light' | 'dark' | 'system'; @Service() export class Theme { private readonly system = inject(ColorScheme); private readonly preference = signal('system'); readonly className = computed(() => { const chosen = this.preference() === 'system' ? this.system.current() : this.preference(); return chosen === 'dark' ? 'dark' : ''; }); choose(preference: Preference): void { this.preference.set(preference); } } ``` The switcher calls `choose('light')`, `choose('dark')` or `choose('system')`. To preserve the preference across launches, save and restore it through the app's settings storage. The example does not persist it. A class retheme covers the app's own CSS only. To switch everything, the native chrome too (headers, switches, sheets, the keyboard), set the scheme on the window with `ColorScheme.set`: ```ts inject(ColorScheme).set('dark'); // the whole app is dark, whatever the system says inject(ColorScheme).set(null); // back to the system's ``` `prefers-color-scheme`, `light-dark()` and `ColorScheme.current` all follow it, so nothing else has to know. ## Tokens cross component boundaries CSS custom properties cascade down the node tree into child components. Ordinary rules match only their component's nodes because sheets attach to component classes, providing emulated encapsulation without per-element markers. A parent can retheme child internals through `--primary`, but cannot select them directly. This includes Tailwind's theme. An element that sets `--color-brand` or `--spacing` recolours or respaces every utility inside it that reads that token, as on the web, however the token is set: in a component stylesheet, a `style` attribute, a `[style.--color-brand]` binding or from code. ```html ``` A bound declaration reads a token too, where its whole value is the `var()`: `[style.background-color]="'var(--color-brand)'"`, with a fallback if it needs one. It follows the token as a stylesheet declaration does. A `var()` inside a longer value, a `calc()` included, is not read from a binding: set a custom property and read that in the stylesheet. Every theme token is resolved on device, where it is read: colours, including the `color-mix()` behind shadow colours and opacity modifiers, bare channels such as `--primary: 0 100% 50%` read through `hsl(var(--primary))`, lengths and the spacing scale's `calc()`s and `max()`s, transition durations and curves, `animate-*` animations, and the `blur-*` and `drop-shadow-*` filters. Where a utility reads one in a form native cannot resolve on device, that declaration takes the theme value at build time instead, and Metro prints a warning naming it. A theme token defined as another, `--color-primary: var(--color-blue-500)`, is worked out where the theme defines it, as on the web: setting `--color-blue-500` on an element does not change `bg-primary` inside it. Set `--color-primary` itself to do that. Resolving tokens on device costs little. Nodes that match the same rules under the same parent share one resolved style, so a list of identical rows resolves its tokens once. ## Reading a token from TypeScript Some places take a colour as a value rather than as a style: a prop on a native view, a colour passed to a library, a drawing that paints each series its own colour. `injectToken` from `@ng-native/device` reads a custom property's value for them, so the stylesheet stays the one place the palette is defined. ```ts import { Component, signal } from '@angular/core'; import { Switch } from '@ng-native/components'; import { injectToken } from '@ng-native/device'; @Component({ selector: 'app-setting', imports: [Switch], template: ``, }) export class Setting { protected readonly on = signal(false); protected readonly accent = injectToken('--accent'); } ``` It returns a signal of the value as text, `rgb(255, 0, 0)` or `12px`, with aliases, `color-mix()` and fallbacks worked out as the stylesheet works them out. On iOS and Android it updates when the colour scheme, another media condition or a stylesheet changes the token. A token holding `platform-color()` reads as that text. The signal is `undefined` where nothing defines the token, and where the token holds a value with no text form here: a shadow, a gradient or other background layers, a filter, a transform, or bare colour channels such as `13, 110, 253`. Without options it reads the token at the root, the scope of `:root` rules, and has a value from the start. To read it where a class lower in the tree sets it again, pass a node: `injectToken('--accent', { at: inject(ElementRef).nativeElement })`. On iOS and Android that value arrives once the node has been committed, so the signal is `undefined` until then. On the web it reads the browser's computed value, at the mount point or at the node, which keeps a `color-mix()` as written. It updates when a class or inline style changes under the mount point or a node is put in or taken out. The `dark` class `mount` keeps in step with the system is one such class, so a `prefers-color-scheme` query is followed while `mount` keeps it. Other media queries, and stylesheets added later, are not followed on the web. An icon's own markup can take a colour from a token. In ``, where `markup` holds `` or the same in `style`, the shape's `fill` or `stroke` is resolved against the tokens in scope at the icon, as the same declaration in a stylesheet is, with a `var()` fallback used when the token is unset. ## Unsupported values and font fallbacks A unitless `line-height` value such as `calc(1.75 / 1.125)` inside a custom property leaves `text-lg` empty until build-time substitution resolves it. Unsupported values produce line-numbered diagnostics. Font stacks are a silent exception. `--font-sans` is a list, but native `fontFamily` accepts one name: `font-family: Inter, Helvetica, sans-serif` becomes `Inter`, discarding the rest without a warning. Native has no fallback stack. If the first font is unavailable or a CSS generic such as `ui-monospace`, text silently uses the system font. Name and verify a bundled font. --- # Build a form ## Install Signal Forms Install `@angular/forms` at your app's exact `@angular/core` version, shown by `npm ls @angular/core`. It is not a framework dependency. A mismatch causes `ERESOLVE` because `@angular/forms` requires matching `@angular/core` and `@angular/common` peers: ```sh npm install @angular/forms@ ``` Signal Forms binds directly to native control models: `form()` expects `value`, or `checked` for boolean controls. `` and `` expose these names. `@ng-native/components` uses this contract rather than `ControlValueAccessor`, which it does not support and never will. ## Define the form `form()` from `@angular/forms/signals` takes a data signal and a schema that adds validators to field paths: ```ts import { Component, signal } from '@angular/core'; import { FormField, form, minLength, required } from '@angular/forms/signals'; import { Switch, Text, TextInput, View } from '@ng-native/components'; @Component({ selector: 'app-sign-up', imports: [FormField, TextInput, Switch, Text, View], template: ` @if (f.name().touched() && f.name().invalid()) { {{ f.name().errors().length }} error(s) } Subscribe to updates `, }) export class SignUp { protected readonly data = signal({ name: '', subscribed: false }); protected readonly f = form(this.data, (path) => { required(path.name); minLength(path.name, 3); }); } ``` `data` is the readable, writable state signal; `f` is its field tree, and `[formField]` binds a control to a path. `FormField`, `form`, `required` and `minLength` come from Angular's `@angular/forms/signals`. Include `FormField` in the component's `imports`. Without it, `[formField]` compiles but has no consumer: the control stays empty and the form invalid. This build does not run the browser compiler's usual "Can't bind to 'formField'" check. Instead, development builds log the element and missing import. The same applies to `ngModel` and Reactive Forms directives. ## Why no adapter class was needed `` exposes `value` as a `model()`; `` exposes `checked` as a `model()`. These names let `FormField` provide two-way binding, disabled/readonly state and touched-on-blur handling. See [Text input](/packages/components/input#the-signal-forms-contract) for the mapping of `disabled()`/`readonly()` to `editable` and `invalid`/`touched` to `data-invalid`/`data-touched` for CSS. ## Style invalid state Style the `data-*` attributes published by `FormField` and the control, as with press-state selectors: ```css text-input { border-width: 1px; border-color: #3a3a42; border-radius: 8px; padding: 12px; } text-input[data-invalid][data-touched] { border-color: #ff6b6b; } ``` ## Submit the form `submit()` runs your action only for a valid form and reports the outcome. Add a button, API call and status display: ```ts import { Component, signal } from '@angular/core'; import { FormField, form, minLength, required, submit } from '@angular/forms/signals'; import { Pressable, Switch, Text, TextInput, View } from '@ng-native/components'; /** Stands in for your own API call. Resolves false for a name that is already taken. */ async function createAccount(data: { name: string; subscribed: boolean }): Promise { return data.name !== 'ada'; } @Component({ selector: 'app-sign-up', imports: [FormField, Pressable, TextInput, Switch, Text, View], template: ` @if (f.name().touched() && f.name().invalid()) { {{ f.name().errors().length }} error(s) } Subscribe to updates {{ f().submitting() ? 'Signing up…' : 'Sign up' }} @switch (status()) { @case ('success') { You're signed up. } @case ('error') { Fix the errors above, then try again. } } `, }) export class SignUp { protected readonly data = signal({ name: '', subscribed: false }); protected readonly status = signal<'idle' | 'success' | 'error'>('idle'); protected readonly f = form(this.data, (path) => { required(path.name); minLength(path.name, 3); }); protected async save(): Promise { await submit(this.f, { action: async () => { const created = await createAccount(this.data()); if (!created) { return { kind: 'taken', message: 'That name is already taken.', fieldTree: this.f.name }; } this.status.set('success'); return; }, onInvalid: () => this.status.set('error'), }); } } ``` `submit()` first marks every field touched, showing errors without waiting for blur. For an invalid field tree, it calls `onInvalid` and resolves without running `action`. Only valid forms reach `createAccount`, the example API call. `f().submitting()` stays true during `action`, disabling the button and changing its label through signal bindings. `action` can return a validation error after validation passes. When `createAccount` returns `false`, the example names `f.name` as the error's `fieldTree`, so `f.name().errors()` exposes it like a client-side validation error. ## Arrays An order, a quote or an invoice is a form with an array of items. An array in the model is an array of fields in the form: `@for` runs over it, and each item goes to a component of its own as a `FieldTree`: ```ts import { Component, input, signal } from '@angular/core'; import { FormField, applyEach, form, required, type FieldTree } from '@angular/forms/signals'; import { Pressable, Text, TextInput } from '@ng-native/components'; interface Line { name: string; cents: number; } @Component({ selector: 'app-line', imports: [FormField, Text, TextInput], template: ` @if (line().name().touched() && line().name().invalid()) { Name is required } `, }) export class LineCard { readonly line = input.required>(); } @Component({ selector: 'app-order', imports: [LineCard, Pressable, Text], template: ` @for (line of f.lines; track line) { } Add a line `, }) export class Order { readonly order = signal<{ lines: Line[] }>({ lines: [{ name: '', cents: 0 }] }); readonly f = form(this.order, (path) => applyEach(path.lines, (line) => required(line.name))); protected add(): void { this.f.lines().value.update((lines) => [...lines, { name: '', cents: 0 }]); } } ``` Adding, removing and reordering are updates of the array's own value, `f.lines().value.update()`. An item's field keeps its identity through a move, so what was typed into it, its `touched` and its errors follow the item, and `track line` moves its card rather than building another. `applyEach` gives every item the same rules, and an item's error goes when the item does. **A control with a model of another name takes a two-way binding.** `[formField]` binds a control whose model is `value` or `checked`. One whose model is called something else, a price field with a `cents` model, is bound to the field's own value instead: ```html ``` **The model is not deeply equal to the data it was given.** Signal Forms keys each item of an array with a symbol, so `expect(order()).toEqual({ lines: [...] })` fails on the key. `toMatchObject` compares the properties it is given and passes. **A long array costs more per keystroke.** The form's model is one signal, so a keystroke asks every field of every item whether it changed, though only the one line is committed, and a `` mounts a card for every item when the form opens. For hundreds of items, a [``](/packages/components/lists) mounts only the rows on screen. --- # Working offline Phone apps need to work through frequent connection losses. Use four steps: 1. Show cached data immediately, without waiting for a network request. 2. When connected, fetch fresh data and update the screen and cache. 3. When offline, keep displaying the cache. 4. Queue offline writes and send them on reconnection, preserving data without blocking the UI. Combine [`Network`](/packages/expo/network) for connectivity, [`Storage`](/packages/expo/storage) or [`Database`](/packages/expo/database) for caching, and `HttpClient` for requests. No new package is needed. ## Pick the cache: `Storage` or `Database` - **`Storage`** (or `SecureStorage`) holds individual preferences, flags or objects through a two-way signal, `store.signal('key', initial)`. Each read returns the whole value; it cannot query, filter or sort lists. - **`Database`** uses `expo-sqlite`, opened and migrated by `database()`, for feeds, search results and paginated rows. `SELECT ... WHERE ... ORDER BY` handles caches beyond a handful of items; `Storage` has no equivalent. The feed below uses `Database`. Use `Storage` for small values such as a last-synchronized timestamp; see the [Storage guide](/packages/expo/storage). ## The worked example: a note feed Declare the schema and migrations as a module-level value; [Database](/packages/expo/database) explains why this is a value rather than a service: ```ts // notes-db.ts import { database } from '@ng-native/expo/database'; export const notesDb = database('notes.db', [ { to: 1, up: (db) => db.execAsync(` CREATE TABLE note (id TEXT PRIMARY KEY, body TEXT NOT NULL, updated_at INTEGER NOT NULL); CREATE TABLE pending_write ( seq INTEGER PRIMARY KEY AUTOINCREMENT, id TEXT NOT NULL, body TEXT NOT NULL ); `), }, ]); ``` `pending_write` queues notes until the server receives them. Sort explicitly by `seq` to send oldest first; database row order is not guaranteed. The service reads the cache, refreshes online, and queues and flushes writes. It keeps the queue in memory and in `pending_write`. Unlike `Storage` and `Network`, `Database` throws without `expo-sqlite` (see [Without the module](/packages/expo/database#without-the-module)). Each `notesDb` call therefore has its own `try`/`catch`. The running app reads and flushes the in-memory `queue`; SQLite persists it across restarts. Node tests and browser previews without `expo-sqlite` lose persistence, but the queue still works. ```ts // notes.ts import { Service, inject, signal, effect, type Signal } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { firstValueFrom } from 'rxjs'; import { Network } from '@ng-native/expo/network'; import { notesDb } from './notes-db.ts'; export interface Note { readonly id: string; readonly body: string; readonly updatedAt: number; } /** A queued write not yet sent, kept in memory so the queue works with no SQLite - see above. */ interface PendingWrite { readonly seq: number; readonly id: string; readonly body: string; } const nextId = () => Date.now().toString(36) + Math.random().toString(36).slice(2, 8); @Service() export class Notes { private readonly http = inject(HttpClient); private readonly network = inject(Network); private readonly list = signal([]); private readonly queue = signal([]); private readonly refreshing = signal(false); private flushing = false; private seq = 0; readonly notes: Signal = this.list.asReadonly(); readonly isRefreshing: Signal = this.refreshing.asReadonly(); constructor() { void this.loadFromCache(); // `connected` flips true the moment there is a network of any kind - see "reachable is not // connected" below for why this reads `connected`, not `reachable`. effect(() => { if (this.network.connected()) void this.refresh(); }); } /** * Cached rows, and the queue as it stood at the last launch, on screen immediately - this is * what a cold, offline start shows. The `catch` is what keeps a platform with no SQLite from * failing to start at all: no cache and an empty queue is exactly what a genuinely cold start * looks like anyway. */ private async loadFromCache(): Promise { try { const db = await notesDb.ready(); this.list.set( await db.getAllAsync( 'SELECT id, body, updated_at as updatedAt FROM note ORDER BY updated_at DESC', ), ); const pending = await db.getAllAsync( 'SELECT seq, id, body FROM pending_write ORDER BY seq', ); this.queue.set(pending); this.seq = pending.reduce((max, write) => Math.max(max, write.seq), 0); } catch { // No SQLite on this platform (Node under a test, a browser preview) - nothing was ever // written to read back, so an empty cache and an empty queue are the correct answer. } } /** * Fresh data when there is a connection; the cache already on screen is the offline fallback. * The in-memory `queue`, not a query against `pending_write`, decides which notes are still * local creations the server has not seen yet, so a refresh merges correctly whether or not * SQLite is there to ask. */ async refresh(): Promise { this.refreshing.set(true); try { await this.flushPendingWrites(); const fresh = await firstValueFrom(this.http.get('https://example.com/notes')); // Drop only notes the server no longer has and that are not still queued to be sent - a // pending note is never removed by a merge, only by a successful flush. const pendingIds = new Set(this.queue().map((write) => write.id)); const freshIds = new Set(fresh.map((note) => note.id)); const kept = this.list().filter((note) => pendingIds.has(note.id) && !freshIds.has(note.id)); this.list.set([...fresh, ...kept]); await this.persistAll(); } catch { // Offline, or the server is unreachable - the request fails and the cache stays exactly as // it was. There is no separate "offline branch" to write; not updating is the fallback. } finally { this.refreshing.set(false); } } /** Optimistic: the note is on screen and queued before the server has seen it. */ async add(body: string): Promise { const note: Note = { id: nextId(), body, updatedAt: Date.now() }; this.list.update((notes) => [note, ...notes]); const write: PendingWrite = { seq: ++this.seq, id: note.id, body: note.body }; this.queue.update((writes) => [...writes, write]); await this.persistNote(note); if (this.network.connected()) void this.flushPendingWrites(); } /** * Sends whatever is queued, oldest first by `seq`, and stops at the first failure to try again * later. `flushing` serialises this against itself, so a reconnect and a fresh `add()` calling * it at the same moment cannot send the same write twice. Reads and removes from the in-memory * `queue`; `pending_write` is a mirror of it kept for the next launch, not what this reads. */ private async flushPendingWrites(): Promise { if (this.flushing) return; this.flushing = true; try { const ordered = [...this.queue()].sort((a, b) => a.seq - b.seq); for (const write of ordered) { try { await firstValueFrom(this.http.post('https://example.com/notes', write)); this.queue.update((writes) => writes.filter((w) => w.seq !== write.seq)); await this.deletePendingRow(write.id); } catch { break; // still offline, or the server rejected it - leave the rest queued and retry later } } } finally { this.flushing = false; } } /** * The note and its queue entry, committed together in one transaction - a failure between the * two statements would otherwise leave a note with nothing that ever sends it. Best-effort, like * every SQLite call from here down: the `queue` signal above is what actually gets flushed, so * losing this write is losing durability across a restart, not losing the write. */ private async persistNote(note: Note): Promise { try { const db = await notesDb.ready(); await db.withTransactionAsync(async () => { await db.runAsync( 'INSERT INTO note (id, body, updated_at) VALUES (?, ?, ?)', note.id, note.body, note.updatedAt, ); await db.runAsync('INSERT INTO pending_write (id, body) VALUES (?, ?)', note.id, note.body); }); } catch { // No SQLite on this platform - the in-memory queue above is what actually gets flushed. } } /** Mirrors `refresh()`'s merged list into `note`, wholesale - simpler than reconciling row by * row, and cheap enough for a cache this size. Best-effort, as above. */ private async persistAll(): Promise { try { const db = await notesDb.ready(); await db.withTransactionAsync(async () => { await db.runAsync('DELETE FROM note'); for (const note of this.list()) { await db.runAsync( 'INSERT INTO note (id, body, updated_at) VALUES (?, ?, ?)', note.id, note.body, note.updatedAt, ); } }); } catch { // No SQLite on this platform. } } private async deletePendingRow(id: string): Promise { try { const db = await notesDb.ready(); await db.runAsync('DELETE FROM pending_write WHERE id = ?', id); } catch { // No SQLite on this platform. } } } ``` The [Notes example](/examples/notes) runs this with a sync-status pill and a settings toggle to disable sync. The component only reads signals and calls methods; it needs no offline-specific logic: ```ts // note-feed.ts import { Component, inject, signal } from '@angular/core'; import { Pressable, Text, TextInput } from '@ng-native/components'; import { Notes } from './notes.ts'; @Component({ selector: 'app-note-feed', imports: [Pressable, Text, TextInput], template: ` @if (notes.isRefreshing()) { Refreshing… } @for (note of notes.notes(); track note.id) { {{ note.body }} } Add `, }) export class NoteFeed { protected readonly notes = inject(Notes); protected readonly draft = signal(''); protected addNote(): void { const body = this.draft().trim(); if (!body) return; void this.notes.add(body); this.draft.set(''); } } ``` Provide `HttpClient` once through `provideNativeHttpClient()` in `mount()`; see [HTTP requests](/packages/platform#http-requests): ```ts import { provideNativeHttpClient } from '@ng-native/platform/http'; mount(rootTag, App, getFabricUIManager(), { providers: [provideNativeHttpClient()], }); ``` ## An interceptor, for the same reconnect signal everywhere The `effect` handles one feed's reconnection. Use an `HttpInterceptorFn` for request-wide behavior, such as retrying a failed `GET` once or tagging requests sent offline for the server: ```ts import type { HttpInterceptorFn } from '@angular/common/http'; import { catchError, throwError } from 'rxjs'; export const offlineAwareInterceptor: HttpInterceptorFn = (req, next) => next(req).pipe( catchError((error) => { // A network failure here is XHR's own error, not an HTTP status - there was no response to // have a status. Distinguish it from a real 4xx/5xx before deciding whether to retry. if (error.status === 0) { console.warn(`[offline] ${req.method} ${req.url} did not reach the server`); } return throwError(() => error); }), ); ``` ```ts import { withInterceptors } from '@angular/common/http'; import { provideNativeHttpClient } from '@ng-native/platform/http'; mount(rootTag, App, getFabricUIManager(), { providers: [provideNativeHttpClient(withInterceptors([offlineAwareInterceptor]))], }); ``` ## Pitfalls ### `reachable` is not proof a request will land [`Network`](/packages/expo/network) distinguishes a connection (`connected`) from the platform's internet-reachability estimate (`reachable`). The estimate is `null`, not `false`, until known; on iOS it equals `connected`. It informs the UI but does not probe your server. A banner checking `reachable === false` must treat `null` on `reachable` as unknown, not offline. The `refresh()` effect uses `connected` to decide whether to try a request. The `try`/`catch` handles unreachable servers even when `Network` reports internet access. Waiting for `reachable` would skip the first cold-start refresh while the estimate is unsettled. ### `HttpClient` needs `provideNativeHttpClient()` Plain `provideHttpClient()` silently returns null bodies wherever the global `fetch` is React Native's own, because its default `fetch` backend cannot read that response's body. The feed can appear offline, and its `catch` blocks do not resolve the ambiguity. Always use `provideNativeHttpClient()`; see [Known limitations](/guide/limitations#httpclient-needs-providenativehttpclient). ### The queue needs an order, a transaction, and a stopping point `flushPendingWrites()` sorts by `seq`, sends oldest first and stops at the first failure, leaving it queued. Reordering changes the user's write sequence; continuing after failure can leave a stuck write retrying indefinitely alongside later writes. The `flushing` flag prevents concurrent flushes when reconnection coincides with a new write. `add()` inserts the note and queue entry in one transaction, preventing crashes or write failures from leaving unsendable notes. `refresh()` merges server data into the cache and preserves queued notes absent from the response because the server has not confirmed them. ### `Database` is not inert without `expo-sqlite` - the queue has to be Without native modules, `Network.connected()` returns `false` and `Storage` signals retain their `initial` values. `Database` instead rejects `notesDb.ready()` on purpose: pretending to hold rows it does not have would be worse than saying so. See [Without the module](/packages/expo/database#without-the-module). A SQLite-only cache and queue therefore fail entirely without the module. If `loadFromCache()` or `add()` awaits `notesDb.ready()` without `try`/`catch`, it rejects before queuing writes. These unawaited calls produce unhandled rejections in Node tests and browser previews without `expo-sqlite`. Keep `queue` as the running app's source of truth. Wrap each `notesDb` call in `try`/`catch` so persistence failures cannot stop dependent operations. SQLite adds durability underneath in-memory state that already works without it - the same graceful-fallback contract `Network` and `Storage` follow automatically, kept by hand here because `Database` will not keep it for you. The [Notes example](/examples/notes) uses this pattern in `sync/notes.ts`; its tests exercise the feed, queue and merge in Node without `expo-sqlite`. --- # Create Expo Module [`@ng-native/expo`](/packages/expo) covers Expo's own modules, and any other Expo module can be [used directly](/packages/expo/using-a-module). When no package does what the app needs, you can either write a local Expo module in Swift and Kotlin (this guide) or [use NativeScript](/guide/native-modules/nativescript) to call iOS and Android platform APIs directly from TypeScript. An Angular app's native module is an ordinary Expo module: the Swift and Kotlin are the same as for any Expo app. Only the JavaScript side is different, because the module is reached through an injected service rather than a React hook. This guide builds a module that reports the device's thermal state, so an app can do less work when the phone is hot. It has one of each thing a module can expose to JavaScript: | Native | Name | What it does | | --------------- | ------------------ | ---------------------------------------------------- | | `Constant` | `supported` | Whether the platform reports a thermal state at all. | | `Function` | `getState` | The state now, answered synchronously. | | `AsyncFunction` | `getHeadroomAsync` | How close the device is to throttling, as a promise. | | `Events` | `onChange` | Fires when the state changes. | A native module needs a development build: [Expo Go](https://expo.dev/go) contains only the native modules it was built with, so it cannot load one you wrote. You need Xcode for iOS and Android Studio for Android. ## Create the module From the root of the app, generate a local module with Expo's scaffolding tool: ```sh npx create-expo-module@latest --local thermal \ --name Thermal \ --package expo.modules.thermal \ --platform apple android \ --features Constant Function AsyncFunction Event ``` A local module lives in `modules/` inside the app, and Expo's autolinking finds it there with no entry in `package.json`. The command creates: ```text modules/thermal/ expo-module.config.json # which native classes are modules, per platform ios/Thermal.podspec ios/ThermalModule.swift android/build.gradle android/src/main/java/expo/modules/thermal/ThermalModule.kt src/ThermalModule.ts # a React-style wrapper src/ThermalModule.web.ts src/Thermal.types.ts ``` Delete `modules/thermal/src`. Its wrapper imports `expo` statically and calls `requireNativeModule`, which throws where the module is not in the build. The service below does that job instead. ```sh rm -rf modules/thermal/src ``` ## Write the Swift Replace `modules/thermal/ios/ThermalModule.swift`. `Name` is the name JavaScript asks for, and each other entry in the definition is one member of the object JavaScript receives: ```swift import ExpoModulesCore public class ThermalModule: Module { private var observer: NSObjectProtocol? public func definition() -> ModuleDefinition { Name("Thermal") Events("onChange") Constant("supported") { true } Function("getState") { Self.state() } AsyncFunction("getHeadroomAsync") { () -> Double? in nil // iOS has no headroom forecast } OnStartObserving { self.observer = NotificationCenter.default.addObserver( forName: ProcessInfo.thermalStateDidChangeNotification, object: nil, queue: nil ) { [weak self] _ in self?.sendEvent("onChange", ["state": Self.state()]) } } OnStopObserving { if let observer = self.observer { NotificationCenter.default.removeObserver(observer) } self.observer = nil } } private static func state() -> String { switch ProcessInfo.processInfo.thermalState { case .fair: return "fair" case .serious: return "serious" case .critical: return "critical" default: return "nominal" } } } ``` `OnStartObserving` runs when JavaScript adds the first `onChange` listener and `OnStopObserving` when it removes the last, so the module observes the system only while something is listening. Returning `nil` from an `AsyncFunction` resolves the promise with `null`. ## Write the Kotlin Replace `modules/thermal/android/src/main/java/expo/modules/thermal/ThermalModule.kt`. The definition has the same names, so JavaScript sees the same object on both platforms: ```kotlin package expo.modules.thermal import android.content.Context import android.os.Build import android.os.PowerManager import expo.modules.kotlin.modules.Module import expo.modules.kotlin.modules.ModuleDefinition class ThermalModule : Module() { private val powerManager get() = appContext.reactContext!!.getSystemService(Context.POWER_SERVICE) as PowerManager private val listener by lazy { PowerManager.OnThermalStatusChangedListener { status -> sendEvent("onChange", mapOf("state" to name(status))) } } override fun definition() = ModuleDefinition { Name("Thermal") Events("onChange") // Thermal status arrived in Android 10 (API 29). Constant("supported") { Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q } Function("getState") { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) name(powerManager.currentThermalStatus) else "nominal" } AsyncFunction("getHeadroomAsync") { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) return@AsyncFunction null val headroom = powerManager.getThermalHeadroom(10) if (headroom.isNaN()) null else headroom.toDouble() } OnStartObserving { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { powerManager.addThermalStatusListener(listener) } } OnStopObserving { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { powerManager.removeThermalStatusListener(listener) } } } private fun name(status: Int) = when (status) { PowerManager.THERMAL_STATUS_NONE -> "nominal" PowerManager.THERMAL_STATUS_LIGHT, PowerManager.THERMAL_STATUS_MODERATE -> "fair" PowerManager.THERMAL_STATUS_SEVERE -> "serious" else -> "critical" } } ``` Android reports seven levels and iOS four. The module maps Android's onto iOS's names, so the service has one set of states to handle. ## Wrap it as a service The service is the only file that knows the native module exists. Everything else injects `Thermal` and reads signals. Create `src/thermal/thermal.ts`: ```ts import { DestroyRef, InjectionToken, Service, inject, signal } from '@angular/core'; export type ThermalState = 'nominal' | 'fair' | 'serious' | 'critical'; /** What modules/thermal declares natively, written out for TypeScript. */ export interface NativeThermal { readonly supported: boolean; getState(): ThermalState; getHeadroomAsync(): Promise; addListener( event: 'onChange', listener: (event: { state: ThermalState }) => void, ): { remove(): void }; } @Service() export class Thermal { /** The native module, or null where it is not in the build. Overridden in tests. */ static readonly NATIVE = new InjectionToken('Thermal.native', { // Required lazily: a static import of 'expo' cannot load in Node, where tests run. factory: () => typeof require === 'function' ? (require('expo') as typeof import('expo')).requireOptionalNativeModule( 'Thermal', ) : null, }); private readonly native = inject(Thermal.NATIVE); private readonly current = signal(this.native?.getState() ?? 'nominal'); readonly state = this.current.asReadonly(); readonly supported = this.native?.supported ?? false; constructor() { const subscription = this.native?.addListener('onChange', ({ state }) => this.current.set(state), ); inject(DestroyRef).onDestroy(() => subscription?.remove()); } /** How close the device is to throttling, 0 to 1. Null on iOS and before Android 11. */ headroom(): Promise { return this.native?.getHeadroomAsync() ?? Promise.resolve(null); } } ``` Each part has a reason: - **`NativeThermal`** is the native definition written out in TypeScript. Nothing checks it against the Swift and Kotlin, so a name spelled differently on one side is `undefined` at run time. Keep the two in step by hand. - **`requireOptionalNativeModule`** answers `null` rather than throwing where the module is not in the build: Expo Go, or a development build made before the module existed. The service then reports `nominal` and `supported: false` instead of crashing the screen that injected it. - **`require` inside the factory**, rather than `import { requireOptionalNativeModule } from 'expo'` at the top of the file. `expo` pulls in `react-native`, which Node cannot load, so a static import fails every test that reaches this file, even one that never uses the module. Metro bundles the `require` exactly as it would an import. In a test, [the Vitest plugin](/packages/testing/setup) hides `require`, so the factory answers `null`. - **The `NATIVE` token** is the seam for tests. It carries its own factory, so the app provides nothing, and a test provides a fake in its place. - **Signals for state, a promise for a one-off question.** The event keeps `state` current, and the listener is removed when the service is destroyed. ## Use it in a component Inject the service and read it like any other signal. This is the template's `App` with thermal state added: ```ts import { Component, inject, resource, signal } from '@angular/core'; import { Pressable, SafeAreaProvider, SafeAreaView, Text, View } from '@ng-native/components'; import { StatusBar } from '@ng-native/device'; import { Thermal } from '../thermal/thermal.ts'; @Component({ imports: [Pressable, SafeAreaProvider, SafeAreaView, Text, View], selector: 'app-root', template: ` Angular, natively Real native views. React is never in the render path. Tapped {{ count() }} times Thermal state: {{ thermal.state() }} Supported: {{ thermal.supported }} Headroom: {{ headroom.value() ?? 'unknown' }} `, styles: ` /* unchanged from the template */ `, }) export class App { protected readonly count = signal(0); protected readonly thermal = inject(Thermal); protected readonly headroom = resource({ loader: () => this.thermal.headroom() }); constructor() { inject(StatusBar).set({ style: 'auto' }); } } ``` ## Test it Tests run in Node, where there is no native module. Provide a fake for `Thermal.NATIVE` and the service runs against it unchanged. Create `src/thermal/thermal.test.ts`: ```ts import { render, screen } from '@ng-native/testing'; import { expect, test } from 'vitest'; import { App } from '../app/app.ts'; import { Thermal, type NativeThermal, type ThermalState } from './thermal.ts'; test('shows the thermal state and follows its changes', async () => { let emit: (event: { state: ThermalState }) => void = () => {}; const fake: NativeThermal = { supported: true, getState: () => 'fair', getHeadroomAsync: async () => 0.4, addListener: (_event, listener) => { emit = listener; return { remove: () => {} }; }, }; await render(App, { providers: [{ provide: Thermal.NATIVE, useValue: fake }] }); expect(screen.getByText('Thermal state: fair')).toBeTruthy(); expect(await screen.findByText('Headroom: 0.4')).toBeTruthy(); emit({ state: 'serious' }); expect(await screen.findByText('Thermal state: serious')).toBeTruthy(); }); test('stays quiet where the module is not in the build', async () => { await render(App, { providers: [{ provide: Thermal.NATIVE, useValue: null }] }); expect(screen.getByText('Thermal state: nominal')).toBeTruthy(); expect(screen.getByText('Supported: false')).toBeTruthy(); }); ``` ```sh npm test ``` A test that provides nothing, such as the template's own `app.test.ts`, also passes: the factory answers `null` in Node, so the service is inert rather than broken. ## Build and run ```sh npx expo run:ios npx expo run:android ``` The first run generates the `ios` and `android` projects, links the module through autolinking, and switches the `ios` and `android` scripts in `package.json` to `expo run:*`. After that: - **A change to TypeScript** reloads through Metro, as usual. - **A change to Swift, Kotlin or `expo-module.config.json`** needs `npx expo run:ios` or `npx expo run:android` again. Fast Refresh does not reload native code. On the iOS simulator the screen shows `Thermal state: nominal`, `Supported: true` and `Headroom: unknown`. `Supported: true` comes from the native constant: without the module it would read `false`. The Android emulator can fake a thermal event, which exercises the whole path from Kotlin to the signal: ```sh adb shell cmd thermalservice override-status 3 # 3 is SEVERE: the screen shows "serious" adb shell cmd thermalservice reset ``` ## On macOS A Mac app runs in the [desktop host](/packages/desktop), which compiles in native code with CMake rather than with Xcode or Gradle, and has no Expo modules runtime, so the Swift and Kotlin above do not reach it. A module's macOS code lives in `modules//macos/`, beside `ios/` and `android/`, and its `expo-module.config.json` can name the CMake target it builds. A library opts in the same way, with `macos` among its `platforms` and a `macos` entry naming its CMake target. A library with a `codegenConfig` gets its specs' codegen, so its C++ TurboModule and its Fabric components build for the Mac as they do for Android. See [Native code](/packages/desktop#native-code). On Linux a module's code lives in `modules//linux/`, and a library lists `linux` among its `platforms` with a `linux` entry, in the same way. `npm run macos` and `npm run package` list the dependencies with native code for iOS or Android and none for the Mac, leaving out `expo-*`, `@expo/*`, `@react-native/*` and `@ng-native/*` packages, which the host answers another way, and those the plugin's `deny` option lists. The listed modules are absent on macOS, so a service built on one reports itself unavailable. ## Going further - **Views.** A module can also render a native view. Add `View` to `--features`, then register the view as an element with `registerExpoView`; see [Native views](/packages/expo/native-views). - **More native API.** The module definition supports more than this page uses: shared objects, typed records for arguments, and `OnCreate`/`OnDestroy` lifecycle hooks. Expo's [Modules API reference](https://docs.expo.dev/modules/module-api/) lists them. Each is exposed to JavaScript the same way, so the service pattern above does not change. - **Sharing it.** To use the module in more than one app, generate it without `--local` to get a standalone package, publish it, and install it like any other Expo module. --- # Use NativeScript Instead of writing Swift and Kotlin modules for each capability, [`@nativescript/react-native`](https://www.npmjs.com/package/@nativescript/react-native) embeds the NativeScript JSI runtime into Hermes. Every iOS SDK symbol (Objective-C classes, protocols, C functions, structs and enums via `libffi`) and Android classpath package (`android.*`, `java.*`, `androidx.*` via JSI/JNI) is callable synchronously from TypeScript, beside Angular signals. [`@ng-native/nativescript`](/packages/nativescript) installs it and gives a component a service to call it through and an element to show a UIView in.
[`examples/nativescript`](https://github.com/ng-native/ng-native/tree/main/examples/nativescript) is a small app using everything on this page. [`nstudio/ng-native-with-ns`](https://github.com/nstudio/ng-native-with-ns) is a complete project on the same runtime: a real-time 3D `SceneKit` viewport and `UIKit` controls on iOS, and an interactive `android.graphics.Canvas` on Android, driven from Angular signals. | Approach | Best when | | ------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- | | [Create Expo Module](/guide/native-modules) | You want a small, self-contained Swift/Kotlin module with a fixed surface area, or you are packaging a reusable Expo module. | | **Use NativeScript** | You want direct, synchronous access to arbitrary iOS and Android SDK APIs and native views from TypeScript without native glue rebuilds. | ## Set it up NativeScript needs a development build (`npx expo run:ios` or `npx expo run:android`), not Expo Go. In an Nx workspace, `nx g @ng-native/nx:nativescript ` does the setup. Anywhere else: ```sh npx expo install @ng-native/nativescript @nativescript/react-native react-native-worklets npm install --save-dev @nativescript/types-android ``` ```json { "expo": { "plugins": ["@ng-native/metro", "@ng-native/nativescript"] } } ``` ```ts // src/nativescript.d.ts /// /// ``` ```ts // src/main.ts const app = mount(Number(rootTag), App, getFabricUIManager(), { providers: [provideNativeScript()], // ...and the rest of the options main.ts already passes. }); ``` Then rebuild the app. [Setup](/packages/nativescript#setup) covers the options, and an app with a `babel.config.js` of its own. ## Call an API `call()` runs the function for the platform the app is on, synchronously, on the JavaScript thread: ```ts import { Component, inject } from '@angular/core'; import { Text } from '@ng-native/components'; import { NativeScript } from '@ng-native/nativescript'; @Component({ selector: 'app-device-name', imports: [Text], template: `{{ model }}`, }) export class DeviceName { private readonly native = inject(NativeScript); protected readonly model = this.native.call({ ios: () => UIDevice.currentDevice.model, android: () => android.os.Build.MODEL, }); } ``` ## Touch the UI UIKit runs only on the main thread, and the component's JavaScript runs on React Native's JavaScript thread. `runOnUI()` runs a worklet on the main thread instead: ```ts protected async tint(): Promise { await this.native.runOnUI(() => { 'worklet'; UIApplication.sharedApplication.keyWindow!.tintColor = UIColor.systemPinkColor; }); } ``` On Android, `runOnUI()` runs the function on the main thread too, in the same runtime. [Calling native APIs](/packages/nativescript/calling-apis) covers what a worklet can read, how it answers later, and what runs where on each platform. ## Show a native view `` shows a view built in a worklet, sized by the template like any other element. On iOS it is a UIView: ```ts import { Component, signal } from '@angular/core'; import { NsView, nsView } from '@ng-native/nativescript'; const torus = nsView<{ wireframe: boolean }, SCNView>({ create(props) { 'worklet'; const view = SCNView.alloc().initWithFrame(CGRectZero); view.scene = SCNScene.scene(); view.allowsCameraControl = true; const geometry = SCNTorus.torusWithRingRadiusPipeRadius(1.4, 0.4); geometry.firstMaterial!.fillMode = props.wireframe ? SCNFillMode.Lines : SCNFillMode.Fill; view.scene!.rootNode.addChildNode(SCNNode.nodeWithGeometry(geometry)); return view; }, update(view, props) { 'worklet'; const geometry = view.scene!.rootNode.childNodes.objectAtIndex(0).geometry!; geometry.firstMaterial!.fillMode = props.wireframe ? SCNFillMode.Lines : SCNFillMode.Fill; }, }); @Component({ selector: 'app-studio', imports: [NsView], template: ``, }) export class Studio { protected readonly torus = torus; protected readonly wireframe = signal(false); } ``` SceneKit is not linked by default, so the route that shows it loads it: `provideNativeScript({ frameworks: ['SceneKit'] })`. [Native views](/packages/nativescript/views) covers props, lifetime, sizing, and the same on Android with an `android.view.View`. ## Test it In Node, where [`@ng-native/testing`](/packages/testing) renders components, there is no NativeScript: `call()` answers `undefined`, `runOnUI()` resolves to `undefined`, and `` is an empty view, so a component using them renders and is tested without a simulator. [In a test](/packages/nativescript#in-a-test) covers giving one native answers. --- # Localization Use Angular's `i18n` in templates, `$localize` in TypeScript, `localize-extract` to extract messages, and `loadTranslations()` from `@angular/localize` to load a language. Unlike the Angular CLI, Metro cannot bake a language into each build. Translations load at runtime before mount, so one build carries every language. Verification covers installation in a template app and iOS/Android bundles through `expo export`. `localisation.test.ts` covers most of the remaining examples through the Metro preset's compiler, except where explicitly noted as unverified. ## Install ```sh npm install @angular/localize@ npm install --save-dev @babel/core@^7.29.0 npx expo install expo-localization expo-secure-store ``` Replace `` with your app's exact `@angular/core` version, shown by `npm ls @angular/core`. It provides `localize-extract`, and its peers include `@angular/compiler` and `@angular/compiler-cli`. [`Locale`](/packages/expo/locale) uses `expo-localization` to read device languages. Omit `expo-secure-store` if the app follows the device rather than remembering an in-app language choice. ### The Babel pin, and why it is not optional `@angular/localize` 22 uses `@babel/core` 8 for build tools. React Native, Metro's Babel plugins and `react-native-worklets` use Babel 7, but React Native declares an unranged `@babel/core` peer. Without a direct Babel 7 dependency, a package manager is free to resolve that peer to Babel 8: - **pnpm** resolves React Native's peer to `@babel/core@8.0.1` in a fresh app or workspace, and the next bundle fails: `[Worklets] Babel plugin exception: Requires Babel "^7.0.0-0", but was loaded with "8.0.1"`. Bundles without worklets still succeed, hiding the problem until worklets are added. - **npm** usually nests Babel 8 under `@angular/localize`, but can hoist it to `node_modules` and nest Babel 7 under each Metro package. That layout bundles, but is unreliable. The `@babel/core@^7` dev dependency makes the peer resolve to Babel 7, keeping Babel 8 private to `@angular/localize`. Neither `@angular/localize/init` nor `loadTranslations()` uses Babel at runtime. Check the installed versions: ```sh pnpm why @babel/core # or: npm ls @babel/core ``` `react-native`, `expo` and `react-native-worklets` should show `7.x`; `8.x` should appear only under `@angular/localize` and `@angular/compiler-cli`. In pnpm workspaces, also pin Babel in the root `package.json`: an unpinned package can move every package's React Native onto Babel 8. ### Load the runtime first `@angular/localize/init` defines the `$localize` global. Import it first in the entry file, before any component module is evaluated: ```ts // src/main.ts import '@angular/localize/init'; import { AppRegistry, Image, Platform, processColor } from 'react-native'; // ...the rest of the entry file ``` ## Mark the text ### In a template `i18n` marks an element's text as a message. Give each one an ID with `@@`, and optionally a meaning and a description for the translator: ```html Your basket Pay now Hello, {{ name() }}! Tap the basket to check out ``` The format is `meaning|description@@id`; all parts are optional. Without an `@@id`, the runtime uses the same text-and-meaning hash as `localize-extract`. Changing the English changes that ID, orphaning its translations. Prefer custom IDs. Interpolations become placeholders (`{$INTERPOLATION}`). Nested elements produce paired placeholders named for the element (`{$START_TAG_TEXT}` and `{$CLOSE_TAG_TEXT}` for a ``), letting translations move styled text to suit their grammar. Use the names from the extracted file: a block inside a message has a pair too, such as `{$START_BLOCK_IF}`. ### In TypeScript `$localize` is a tagged template, with the same `:meaning|description@@id:` block at the front: ```ts protected readonly saveLabel = $localize`:@@editor.save:Save`; protected welcome(name: string): string { return $localize`:@@home.welcome:Welcome back, ${name}:name:!`; } ``` The `:name:` after an expression names its placeholder, `{$name}` in the extracted file; without one it is `{$PH}`. Keep `$localize` inside classes and functions. Class fields evaluate when components are created, after translations load. Module-level constants evaluate on import, before translations load, and remain in the source language. ### Attributes `i18n-` before an attribute's name marks its value as a message, with the same `meaning|description@@id` format: ```html ``` A label built in code is a `$localize` string, bound as any other value: `[accessibilityLabel]="closeLabel"`. ### Plurals and selects An ICU expression chooses between messages by a number or a string, on iOS, Android and the web host. Give it an element of its own, so the whole expression is one message under your ID: ```html {count(), plural, =0 {Your basket is empty} one {One item} other {{{ count() }} items}} {reply().author, select, me {You replied} other {They replied}} ``` A plural takes an exact `=N` case first. Otherwise `LOCALE_ID` selects a category using Angular's locale data, not `Intl`. Include every category your languages need: English uses `one` and `other`; Polish also uses `few` and `many`. Missing categories fall back to `other`. The translation is the same expression with its cases translated. The value it chooses by is `VAR_PLURAL` or `VAR_SELECT`, and an interpolation in a case is `{INTERPOLATION}`: ```json "basket.count": "{VAR_PLURAL, plural, =0 {Votre panier est vide} one {Un article} other {{INTERPOLATION} articles}}" ``` A case holds text and interpolations. An element inside a case, such as ``, is left out with its content; see [Known limitations](/guide/limitations#i18n-is-runtime-only). A case is read as HTML, so write `&` and `<` for `&` and `<` in a translation. Numeric character references are read, and of the named ones only `&`, `<`, `>`, `"`, `'` and ` `. With text beside the expression in the same element, Angular extracts the expression as a second message under a computed ID. For a plural in TypeScript, use Angular's `i18nPlural` pipe with a `$localize` string per form: ```ts import { Component, input } from '@angular/core'; import { I18nPluralPipe } from '@angular/common'; import { Text } from '@ng-native/components'; @Component({ selector: 'app-basket-count', imports: [I18nPluralPipe, Text], template: `{{ count() | i18nPlural: items }}`, }) export class BasketCount { readonly count = input.required(); protected readonly items: Record = { '=0': $localize`:@@basket.empty:Your basket is empty`, one: $localize`:@@basket.one:One item`, other: $localize`:@@basket.other:# items`, }; } ``` `#` becomes the number. To choose a category in code, use `inject(NgLocalization).getPluralCategory(count)` from `@angular/common`: Hermes has `Intl.NumberFormat` and `Intl.DateTimeFormat` but no `Intl.PluralRules`, so `new Intl.PluralRules(...)` throws on device. ## Recipes - [Extracting messages](/guide/localization-extraction) - pulling `messages.json` out of a Metro bundle, and translating a copy of it. - [Loading a language](/guide/localization-loading) - deciding `LOCALE_ID` and loading its translations before the app's first frame. - [Switching language](/guide/localization-switching) - in the app, and following the system. - [Formatting and right to left](/guide/localization-formatting) - dates, numbers, currency, and mirroring a layout. - [Localization with Transloco](/guide/localization-transloco) - the alternative to `i18n` when the language changes inside the app and must not reload it. ## What does not work yet - **Build-time translation** (`localize-translate`, one bundle per language) has no Metro integration or verification. Use runtime translation. - **`ng extract-i18n`** requires an unsupported browser build. Use `localize-extract` on the Metro bundle; see [Extracting messages](/guide/localization-extraction). See [Known limitations](/guide/limitations#i18n-is-runtime-only). --- # Extracting messages After marking templates with `i18n` and TypeScript with `$localize` as in [Localization](/guide/localization), run `localize-extract` on Metro's unminified JavaScript bundle, not Hermes bytecode. It extracts every message from compiled JavaScript: ```sh npx expo export --platform ios --no-bytecode --no-minify --output-dir i18n-build npx localize-extract -s 'i18n-build/**/*.js' -f json -o locale/messages.json rm -rf i18n-build ``` The output for the snippets in [Localization](/guide/localization), trimmed: ```json { "locale": "en", "translations": { "home.title": "Your basket", "home.greeting": "Hello, {$INTERPOLATION}!", "home.hint": "Tap {$START_TAG_TEXT}the basket{$CLOSE_TAG_TEXT} to check out", "editor.save": "Save", "basket.other": "# items" } } ``` Extraction includes template messages and `$localize` strings from app code only. `-f` also accepts `xlf`, `xlf2`, `xmb` and `arb` for translation services. JSON works directly with `loadTranslations()`, without a parser. Copy `messages.json` to `messages.fr.json`, set `"locale": "fr"`, and translate the values, preserving every `{$...}` placeholder: ```json { "locale": "fr", "translations": { "home.title": "Votre panier", "home.greeting": "Bonjour, {$INTERPOLATION} !", "home.hint": "Touchez {$START_TAG_TEXT}le panier{$CLOSE_TAG_TEXT} pour payer", "editor.save": "Enregistrer", "basket.other": "# articles" } } ``` `ng extract-i18n` requires a browser build, which fails for the template app with 164 errors across native properties (`Can't bind to 'zoomScale' since it isn't a known property of 'scroll-view'`), DOM/native event types and React Native's Flow syntax. Next: [Loading a language](/guide/localization-loading) puts `messages.fr.json` into the app. --- # Loading a language With `messages.fr.json` from [Extracting messages](/guide/localization-extraction), define a provider in a separate file to choose and load the language: ```ts // localisation.ts import { registerLocaleData } from '@angular/common'; import localeFr from '@angular/common/locales/fr'; import { LOCALE_ID, inject, makeEnvironmentProviders, provideAppInitializer, type EnvironmentProviders, } from '@angular/core'; import { loadTranslations } from '@angular/localize'; import { Locale } from '@ng-native/expo/locale'; import { getItem } from 'expo-secure-store'; import fr from './locale/messages.fr.json'; /** The language the source text is written in. There is nothing to load for it. */ const SOURCE = 'en'; const TRANSLATIONS: Record> = { fr: fr.translations, }; registerLocaleData(localeFr); /** The first language in the list that this app has, or the source language. */ export function chooseLanguage(preferred: readonly (string | null)[]): string { return ( preferred.find((code) => code === SOURCE || (code != null && code in TRANSLATIONS)) ?? SOURCE ); } export function provideLocalisation(): EnvironmentProviders { return makeEnvironmentProviders([ { provide: LOCALE_ID, useFactory: () => chooseLanguage([ getItem('language'), ...inject(Locale) .locales() .map((locale) => locale.languageCode), ]), }, provideAppInitializer(() => { const messages = TRANSLATIONS[inject(LOCALE_ID)]; if (messages) loadTranslations(messages); }), ]); } ``` Pass it to `mount`: ```ts // src/main.ts const app = mount(Number(rootTag), App, getFabricUIManager(), { // ...processColor, conditions, tokens, resolveAssetSource as before providers: [provideLocalisation()], }); ``` `LOCALE_ID` controls both translation loading and Angular pipe formatting. It selects the in-app choice first (see [Switching language](/guide/localization-switching)), then device languages in preference order. Use `Locale.locales()`, not `Locale.locale()`: if the user prefers German then French, an app without German should choose French rather than English. `mount` runs initializers before creating the root component, so translations must load synchronously. It starts promise-returning initializers without awaiting them; network-fetched translations would arrive after the first frame and template evaluation. Import translations so Metro bundles them. Missing translations fall back to source text and log `No translation found`, so an incomplete file ships a partly English screen rather than a broken one. Unsupported device languages fall back to `SOURCE`. Next: [Switching language](/guide/localization-switching) covers changing `LOCALE_ID` after startup. --- # Switching language After [Loading a language](/guide/localization-loading), calling `loadTranslations()` again changes no existing templates, even after unmounting and remounting. Template messages are evaluated on the component's first render anywhere in the app and cached for the JavaScript runtime's lifetime. `$localize` class fields in newly created components use the new language, producing mixed-language screens. Tests verify both behaviors. Restart JavaScript to switch languages. Expo can reload in place: ```ts import { Component, LOCALE_ID, inject } from '@angular/core'; import { Pressable, Text, View } from '@ng-native/components'; import { reloadAppAsync } from 'expo'; import { setItemAsync } from 'expo-secure-store'; @Component({ selector: 'app-language-picker', imports: [Pressable, Text, View], template: ` @for (language of languages; track language.code) { {{ language.name }} } `, }) export class LanguagePicker { protected readonly current = inject(LOCALE_ID); protected readonly languages = [ { code: 'en', name: 'English' }, { code: 'fr', name: 'Français' }, ]; protected async switchTo(code: string): Promise { if (code === this.current) return; await setItemAsync('language', code); await reloadAppAsync('The language changed'); } } ``` Store the choice where startup can read it _synchronously_, before `LOCALE_ID` is set for the first frame. `expo-secure-store`'s `getItem` can read synchronously; AsyncStorage cannot. Await the write before reloading to avoid a race. Display language names in their own languages so users can recover from an unreadable choice. Alternatively, let the system manage language without app code. With `supportedLocales`, iOS and Android 13+ expose per-app language settings, which `Locale` reports: ```json { "expo": { "plugins": [["expo-localization", { "supportedLocales": ["en", "fr"] }]] } } ``` iOS terminates the app after a Settings language change; the next launch uses the new language. Android's behavior for a running React Native app remains unverified. If necessary, on foreground, compare `chooseLanguage` over `Locale.locales()` with `LOCALE_ID` and reload if they differ. Expo documents `reloadAppAsync` for release and development builds; device behavior remains unverified here. Next: [Formatting and right to left](/guide/localization-formatting) covers dates, numbers and layout mirroring. --- # Formatting and right to left Alongside translations in [Localization](/guide/localization), language affects date and number formatting and layout direction. ## Dates, numbers and currency Angular's `date`, `number`, `percent` and `currency` pipes use `LOCALE_ID` and Angular's locale data. `@angular/common` does not call `Intl`, so Hermes and browsers behave alike without polyfills. English is built in; register other languages once, as [`localisation.ts`](/guide/localization-loading) does with `registerLocaleData(localeFr)`. With `LOCALE_ID` set to `fr`: ```html {{ when | date: 'longDate' }} {{ 1234567.891 | number: '1.0-2' }} {{ 1234.5 | currency: 'EUR' }} ``` French uses narrow and non-breaking spaces, as in a browser. For regional variants (`fr-CA`, `en-GB`), register the matching `@angular/common/locales/` data file and use the full `LOCALE_ID` tag. ### Timezones `date` accepts the same timezones as in a browser through its third argument: offsets such as `'+0530'` or `'-05:00'`, `'UTC'`, `'GMT'`, and North American abbreviations such as `'EST'` or `'PDT'`. `mount()` adds support to Hermes' `Date.parse` for the legacy date form Angular uses to determine the offset. ```html {{ when | date: 'HH:mm' : 'UTC' }} {{ when | date: 'HH:mm' : '+0500' }} ``` Angular does not support named zones such as `'Europe/London'`, in browsers or here. The pipe uses the device's zone and logs a development warning once, naming the unsupported zone. For named zones, use `Intl.DateTimeFormat` with `timeZone`, supported by Hermes: ```ts new Intl.DateTimeFormat('en-GB', { timeZone: 'Asia/Tokyo', timeStyle: 'short' }).format(when); // '23:30' ``` Hermes supports only part of `Intl`, affecting direct callers. The iOS Hermes framework used here provides `Intl.Collator`, `Intl.DateTimeFormat` and `Intl.NumberFormat`, but no `Intl.PluralRules`, `Intl.RelativeTimeFormat` or `Intl.ListFormat`. Angular's [plurals](/guide/localization#plurals-and-selects) read its own locale data instead. Check missing APIs before using them, for example `'PluralRules' in Intl`. Angular's locale data excludes user clock and calendar preferences; an English speaker may use a 24-hour clock. `Locale.calendars()` exposes `uses24hourClock`, `firstWeekday` and `timeZone` to help choose formats such as `'HH:mm'` instead of `'shortTime'`. ## Right to left The platform sets direction at startup, independently of translations. Enable `supportsRTL` in the same plugin entry to lay out a right-to-left language correctly: ```json ["expo-localization", { "supportedLocales": ["en", "ar"], "supportsRTL": true }] ``` React Native chooses direction from the device language at startup; it cannot change while the app runs. The cascade mirrors padding, text alignment and row-child order without stylesheet changes. For TypeScript-calculated positions, such as a drawer's opening edge or a slider's drag direction, use [`Direction`](/packages/device/direction) from `@ng-native/device`. `Locale.rtl()` reports language direction; branch on `Direction` for the actual layout. --- # Localization with Transloco [Localization](/guide/localization) uses Angular's `i18n`, which fixes the language when the app starts: changing it means reloading the JavaScript. [Transloco](https://jsverse.gitbook.io/transloco) looks keys up in a dictionary at runtime instead, so an in-app language picker takes effect on the next frame, with no reload and no mixed-language screens. The cost is that you write a key for each text and keep a JSON file per language, where `i18n` extracts the source text for you. Choose Transloco when users switch language inside the app, or when you already have Transloco translation files and tooling. Choose Angular's `i18n` when the language follows the device and a reload on change is acceptable. Transloco itself needs no change: it touches `window` only behind `typeof` guards. Three things differ from a web app, and each has a section below: - Metro needs literal import paths, and a device has no `assets/` folder to fetch from, so the default HTTP loader does not exist. Use an [inline loader](https://jsverse.gitbook.io/transloco/advanced-features/lazy-load/inline-loaders). - `getBrowserLang()` returns `undefined`, so read the device's language with [`Locale`](/packages/expo/locale) (`expo-localization`) and choose the first language yourself. - The native header does not show a route's `title`, so a title strategy has nothing to show. ## Install ```sh npm install @jsverse/transloco ``` Transloco is a normal Angular library, so it needs no Metro configuration. Add `@jsverse/transloco-messageformat` only if you write ICU plurals (see [Plurals](#plurals)). ## Provide Transloco Register the available languages and the default one. With every file loaded through a scope (see below), no global loader is needed: ```ts // app.config.ts import { isDevMode } from '@angular/core'; import { provideTransloco } from '@jsverse/transloco'; export const appProviders = [ provideTransloco({ config: { availableLangs: ['en', 'fr', 'ar'], defaultLang: 'en', reRenderOnLangChange: true, prodMode: !isDevMode(), }, }), ]; ``` `reRenderOnLangChange` is what re-renders a native template when the language changes. ## Load files with an inline loader On the web, Transloco fetches `assets/i18n/.json` over HTTP. On a device there is nothing to fetch, and Metro resolves `import()` paths at build time, so a path computed from the language (``import(`./i18n/${lang}.json`)``) cannot be bundled. Write one literal `import()` per language. For a feature's own texts, give the feature a scope with an [inline loader](https://jsverse.gitbook.io/transloco/advanced-features/lazy-load/inline-loaders), in the providers of its route. It is the same place a scope is declared on the web, and it needs no central list of files: ```ts // settings.routes.ts import { type Route } from '@angular/router'; import { provideTranslocoScope } from '@jsverse/transloco'; export const SETTINGS_ROUTE: Route = { path: 'settings', providers: [ provideTranslocoScope({ scope: 'settings', loader: { en: () => import('./i18n/settings/en.json'), fr: () => import('./i18n/settings/fr.json'), ar: () => import('./i18n/settings/ar.json'), }, }), ], loadComponent: () => import('./settings-page'), }; ``` The scope's files hold their keys without the scope prefix. Transloco unwraps a JSON module's `default` itself, so the loader returns the `import()` as it is. Enable `resolveJsonModule` in the app's `tsconfig.json`. Keys that several features read belong in the global dictionary. Give `provideTransloco` a `TranslocoLoader` of the same shape, with one literal `import()` per language: ```ts import { Service } from '@angular/core'; import { type Translation, type TranslocoLoader } from '@jsverse/transloco'; @Service() export class AppTranslocoLoader implements TranslocoLoader { async getTranslation(lang: string): Promise { const module = await { en: () => import('./i18n/en.json'), fr: () => import('./i18n/fr.json'), ar: () => import('./i18n/ar.json'), }[lang === 'fr' || lang === 'ar' ? lang : 'en'](); return (module as { default?: Translation }).default ?? module; } } ``` ```ts provideTransloco({ loader: AppTranslocoLoader, config: {/* as above */} }); ``` Each file becomes its own small Metro module in a development bundle, and a release bundle inlines them. A forgotten scope shows its keys, not a blank. ## Translate in a template Use the `transloco` pipe or the structural directive. Both work inside ``. They are standalone, so import `TranslocoPipe` and `TranslocoDirective` in the component that uses them: ```ts import { Component, signal } from '@angular/core'; import { TranslocoDirective, TranslocoPipe } from '@jsverse/transloco'; import { Text } from '@ng-native/components'; @Component({ selector: 'app-settings', imports: [Text, TranslocoPipe, TranslocoDirective], templateUrl: './settings.html', }) export class Settings { protected readonly name = signal('Sam'); } ``` ```html {{ 'settings.title' | transloco }} {{ 'settings.greet' | transloco: { name: name() } }} {{ t('settings.title') }} ``` Write the full key, scope included. Prefer the pipe to `translateSignal()`: under a route that provides the `settings` scope, `translateSignal('settings.title')` prefixes the scope a second time and renders `settings.settings.title`. Do not call `translate()` in a field initializer or a `computed()` that runs before the scope has loaded: it returns the key. A scope loads the first time a `transloco` pipe or directive renders, so translate in the template, or in an event handler. When a component needs a translated string for a prop, translate it where the prop is bound: ```html ``` ### Screen titles Angular still resolves a route's `title` into `ActivatedRoute.snapshot.title`, but the native header does not show it: a screen's title is an input of the header. `provideTranslocoTitleStrategy()` therefore has no visible effect (the document stub makes `Title.setTitle` a no-op that does not throw). Do not use it, and bind the title yourself: ```html ``` ## Choose the first language `getBrowserLang()` returns `undefined` on React Native, because `navigator.language` does not exist. Use [`Locale`](/packages/expo/locale), which wraps `expo-localization`, to read the device's languages, and activate one before the first screen shows. The stored choice wins, then the device's language, then the default. Install the module first: ```sh npx expo install expo-localization expo-secure-store ``` Omit `expo-secure-store` if the app only follows the device and never remembers an in-app choice. ```ts import { inject, provideAppInitializer } from '@angular/core'; import { TranslocoService } from '@jsverse/transloco'; import { Locale } from '@ng-native/expo/locale'; import { getItem } from 'expo-secure-store'; const SUPPORTED = ['en', 'fr', 'ar']; export function pickLanguage( stored: string | null, deviceLanguages: readonly (string | null)[], ): string { if (stored && SUPPORTED.includes(stored)) return stored; // A device locale can have no language code, so skip those. const device = deviceLanguages.find((code) => code != null && SUPPORTED.includes(code)); return device ?? 'en'; } provideAppInitializer(() => { const transloco = inject(TranslocoService); const deviceLanguages = inject(Locale) .locales() .map((locale) => locale.languageCode); transloco.setActiveLang(pickLanguage(getItem('language'), deviceLanguages)); }); ``` `Locale` keeps its list current as the user changes language in the system settings, and lists every preferred locale, not only the first. If you cannot add a native module, `Intl.DateTimeFormat().resolvedOptions().locale` returns the device's first locale on Hermes. ng-native starts `provideAppInitializer` functions but does not wait for them: the first frame does not wait. If a screen must not render before the language is active, hold the router outlet back (for example behind a `ready` signal set after `await lastValueFrom(transloco.load(lang))`). ## Switch language Call `setActiveLang()` and store the choice. The templates update in the same frame, because the pipe re-renders on the language change: ```ts import { Component, inject } from '@angular/core'; import { TranslocoService } from '@jsverse/transloco'; import { Pressable, Text, View } from '@ng-native/components'; import { setItemAsync } from 'expo-secure-store'; @Component({ selector: 'app-language-picker', imports: [Pressable, Text, View], template: ` @for (language of languages; track language.code) { {{ language.name }} } `, }) export class LanguagePicker { private readonly transloco = inject(TranslocoService); protected readonly languages = [ { code: 'en', name: 'English' }, { code: 'fr', name: 'Français' }, ]; protected async switchTo(code: string): Promise { this.transloco.setActiveLang(code); await setItemAsync('language', code); } } ``` Display language names in their own languages so users can recover from an unreadable choice. Compare [Switching language](/guide/localization-switching) for Angular's `i18n`, which has to restart the JavaScript. ## Follow the language with the layout direction Translating to a right-to-left language changes the text, not the layout: views stay left-aligned until something sets a direction. Bind `direction` on the root view from the active language. The cascade mirrors paint and layout for every view under it, so a language change needs no restart. React Native's `I18nManager.forceRTL` does need one, so do not use it for this. Keep the list of your app's right-to-left languages in one place, and derive the direction from it: ```ts // language-direction.ts const RTL_LANGUAGES: readonly string[] = ['ar', 'he', 'fa', 'ur']; export function isRtl(lang: string | undefined): boolean { return !!lang && RTL_LANGUAGES.includes(lang); } ``` ```ts import { Component, computed, inject } from '@angular/core'; import { toSignal } from '@angular/core/rxjs-interop'; import { TranslocoService } from '@jsverse/transloco'; import { isRtl } from './language-direction.ts'; @Component({ selector: 'app-root', template: ``, }) export class App { private readonly lang = toSignal(inject(TranslocoService).langChanges$); protected readonly direction = computed(() => (isRtl(this.lang()) ? 'rtl' : 'ltr')); } ``` A `modal` reads its layout direction from the [`Direction`](/packages/device/direction) service, whose default source asks the device. The device language cannot change while the app runs, and says nothing of a language picked in your settings, so point the source at Transloco: ```ts import { inject } from '@angular/core'; import { TranslocoService } from '@jsverse/transloco'; import { Direction, type DirectionSource, type LayoutDirection } from '@ng-native/device'; import { isRtl } from './language-direction.ts'; function languageDirectionSource(transloco: TranslocoService): DirectionSource { const current = (): LayoutDirection => (isRtl(transloco.getActiveLang()) ? 'rtl' : 'ltr'); return { current, subscribe: (listener) => { const subscription = transloco.langChanges$.subscribe(() => listener(current())); return () => subscription.unsubscribe(); }, }; } // in the app's providers { provide: Direction.SOURCE, useFactory: () => languageDirectionSource(inject(TranslocoService)) }, ``` See [Formatting and right to left](/guide/localization-formatting) for dates, numbers and the rest of mirroring. ## Plurals Transloco's default interpolation has no plurals. `@jsverse/transloco-messageformat` adds ICU `{count, plural, one {...} other {...}}`: ```ts import { provideTranslocoMessageformat } from '@jsverse/transloco-messageformat'; providers: [provideTranslocoMessageformat()]; ``` The plugin builds on `@messageformat/core`, which compiles each message to a function that carries the plural rules of its language (generated from CLDR, languages with many forms included). Neither package calls `Intl.PluralRules`, which Hermes lacks on iOS and Android, so plurals need no polyfill. The runtime does call `Intl.NumberFormat` for number arguments, which Hermes has. ## Extract and validate the keys `transloco-keys-manager` and `transloco-validator` read source files, so they work on ng-native templates as they are. A key is found in these forms, all verified inside native templates: - `{{ 'key' | transloco }}` in a `` or as a prop binding, such as `[title]="'key' | transloco"` - `*transloco="let t"` with `t('key')` - a ternary of two literals, such as `(cond ? 'a.b' : 'a.c') | transloco` - a `marker()` call in TypeScript Give each scope an entry in the `scopePathMap` of `transloco.config.ts`, so its keys land in the scope's file and not in the global one: ```ts // transloco.config.ts import { type TranslocoGlobalConfig } from '@jsverse/transloco-utils'; const config: TranslocoGlobalConfig = { rootTranslationsPath: 'src/i18n/', langs: ['en', 'fr', 'ar'], scopePathMap: { settings: 'src/features/settings/i18n/settings', }, keysManager: { input: ['src'], output: 'src/i18n', }, }; export default config; ``` A key stored as a plain string and only bound later (`{{ item.labelKey | transloco }}`) is invisible to the extractor: wrap it in `marker()` where it is defined. ## Test with Vitest Transloco has to go through Vite with your code. As an external Node module it brings its own copy of `@angular/core`, and `inject()` then fails with `NG0203` (no injection context). Metro bundles one copy, so a device is unaffected. Inline it in `vitest.config.ts`: ```ts import { ngNative } from '@ng-native/testing/vitest'; import { defineConfig } from 'vitest/config'; export default defineConfig({ plugins: [ngNative({ inline: [/\/node_modules\/@jsverse\/transloco/] })], }); ``` A render test can then provide a scope with an inline loader, render a component, and switch language, all in the fake Fabric: ```ts import { provideTranslocoScope } from '@jsverse/transloco'; const scope = provideTranslocoScope({ scope: 'settings', loader: { en: () => Promise.resolve({ title: 'Settings' }), fr: () => Promise.resolve({ title: 'Réglages' }), }, }); ``` Call `transloco.setActiveLang('fr')` and wait for the new text with `findByText`: the old text is gone, with no reload. A component that builds text with `translate()` shows the raw key until the scope has loaded, so wait for the text and do not read it on the first tick. ## Known limits - The native header does not show a route's title, so there is no title strategy to configure. See [Screen titles](#screen-titles). - `Intl.PluralRules`, `Intl.RelativeTimeFormat` and `Intl.ListFormat` are missing from Hermes, so code that calls them directly throws on device. Transloco and its messageformat plugin do not. `Intl.NumberFormat` and `Intl.DateTimeFormat` exist on both platforms, but their output differs: Arabic gets Latin digits on iOS and Arabic-Indic digits on Android, and iOS can round differently. Pass `numberingSystem` and `calendar` explicitly where the two must match. See [Formatting and right to left](/guide/localization-formatting). - Moving to Transloco from Angular's `i18n` is a rewrite of the texts, not of the build: the two do not read each other's files. Transloco has a migration guide from Angular's `i18n` ([link](https://jsverse.gitbook.io/transloco/migration-guides/migrate-from-angulars-i18n)) for the web; the steps for the texts apply to a native app too. --- # Build for the Mac An Angular Native app runs on macOS as a native app: AppKit views drawn by the [desktop host](/packages/desktop), React Native's C++ core and Hermes, with no web view. EAS Build and EAS Update do not build or update macOS apps. You build a Mac app on a Mac, with `npm run package`, and ship new versions of it through Sparkle, which only a `dmg` packaged with `--feed-url` and a public key carries (see [Packaging](/packages/desktop/packaging#the-build)); the `app` that `npm run package` makes has no updater. To build, sign and notarise it on every push, see [Package in GitHub Actions](/guide/desktop-github-actions). ## Start A new app that is only for the Mac starts from the desktop template, whose README is its quick start: ```sh npx create-expo-app@latest my-app --template @ng-native/template-desktop cd my-app npm start # the dev server, in one terminal npm run macos # gets the desktop host the first time, then opens the app ``` Expo is the build tool here, not the runtime: its CLI, config, autolinking and Metro build the app, and the desktop host runs it. To add macOS to an app you have, see [Desktop setup](/packages/desktop#setup), which also covers Nx and the Angular CLI. The template runs on Linux too, with `npm run linux` on a Linux machine: see [Build for Linux](/guide/desktop-linux). ## Linux The same app runs on Linux, with GTK 4 and libadwaita views. [Build for Linux](/guide/desktop-linux) has the setup and packaging. The distributions the host is checked on: | Distribution | Checked | | ----------------------- | --------------------------------------------------------------------------------- | | Ubuntu 24.04 and 26.04 | launched every night in CI | | Debian 13 | launched every night in CI | | Fedora 44 and 45 | launched every night in CI | | RHEL 9 and its rebuilds | the host is built on AlmaLinux 9 on every pull request (GTK 4.12, libadwaita 1.4) | The floor is GTK 4.10 and libadwaita 1.4 with glibc 2.34. A `deb` is made for Debian 13 and Ubuntu 24.04 or later, an `rpm` for Fedora and the RHEL family 9 or later, and a Flatpak brings its own runtime. ## What a Mac app has - **Windows.** The root component renders in the main window, and `AppWindows` opens more: a component in each, or a named outlet of the app's one Router. See [Windows](/packages/device/app-windows). - **Menus.** Every app gets the standard menu bar. ``, `` and `` add to it, `[contextMenu]` gives a view a menu on a secondary click, `[menu]` gives a `` one on a click, and `[shortcut]` a key. See [Menus](/packages/components/menus). - **A sidebar.** ``, ``, `` and `` are the window's source list, and a tab app's tabs become one. See [Sidebar](/packages/components/sidebar). - **The mouse and keyboard.** `:hover`, `:focus-visible`, `cursor`, `(mouseenter)`, `(dblclick)`, `(contextmenu)` and Tab order all work, and `` is an AppKit button. - **Drag and drop.** `(fileDrop)` takes files, text and urls dragged onto a view, and `[dragItem]` lets a view be dragged out. See [Drag and drop](/packages/components/drag-and-drop). - **The system.** The [Dock and a menu bar icon](/packages/device/dock), declared programs, urls and files through [Processes and Shell](/packages/device/processes), and the app's own actions on Edit > Undo through [UndoStack](/packages/device/undo-stack). The pages under this one cover [what differs](/guide/desktop-differences) from iOS and Android, [how big things are](/guide/desktop-sizing) on a Mac, [where each desktop API is imported from](/guide/desktop-imports), [what each OS has](/guide/desktop-support), and how [Electron's APIs](/guide/desktop-electron) map to these. ## Test it `render(X, { os: 'macos' })` renders a component as on macOS, in its main window, with recording fakes of the windows, menus, Dock and tray. See [Testing on another OS](/packages/testing/testing-other-os). An app from the desktop template, or from the generators' desktop-only option, has a Vitest project for each OS in Node and one for each inside the app. `node-macos` and `node-linux` run in Node, and are what `npm test` (`vitest run --project node-macos --project node-linux`) and the app's `test` target run. `macos` runs `src/**/*.device.ts`, such as `src/app/app.device.ts`, inside the app on real AppKit views, and starts Metro and opens the app itself; `linux` does the same in GTK (see [Test Linux from a Mac](/guide/desktop-linux#test-linux-from-a-mac)): ```sh npx vitest --project macos ``` --- # Build for Linux An Angular Native app runs on Linux as a native app: GTK 4 and libadwaita views drawn by the [desktop host](/packages/desktop), React Native's C++ core and Hermes, with no web view. It is the same app, the same APIs and the same tests as the [Mac's](/guide/desktop). This page is what Linux adds: setting up, testing from a Mac, and packaging. ## Start The desktop template runs on both desktop OSes: ```sh npx create-expo-app@latest my-app --template @ng-native/template-desktop cd my-app npm start # the dev server, in one terminal npm run linux # on Linux: gets the GTK host the first time, then opens the app ``` `npm run linux` is `ng-native-desktop run --os linux`, and it runs on Linux only. On a Mac it stops before it fetches or builds anything, and says to run it on a Linux machine or VM, or to make the Linux packages with `npm run package -- --os linux`. From a Mac you test Linux through [`vitest --project linux`](#test-linux-from-a-mac) and ship it with `package`. To add Linux to an app you have, see [Desktop setup](/packages/desktop#setup), which covers `linux` in `expo.platforms`, the `linux` script, Nx and the Angular CLI. `npx expo export -p linux` is refused by Expo until `app.config.js` calls `registerLinux` from `@ng-native/metro/linux.cjs`: ```js // app.config.js require('@ng-native/metro/linux.cjs').registerLinux(__dirname); module.exports = ({ config }) => config; ``` `npm start`, `npm run linux` and `npm run package` do not need it. ## What runs where A Linux package runs on the desktop's own GTK and libadwaita, or, for a Flatpak, on the GNOME runtime it brings. The host is built on AlmaLinux 9, so it needs glibc 2.34 at most. | Library | At least | Where it matters | | --------------- | -------- | ----------------------------------------------------------------------- | | glibc | 2.34 | `deb` and `rpm` | | GTK | 4.10 | `deb` and `rpm`; accessibility announcements need 4.14 | | libadwaita | 1.4 | `deb` and `rpm`; dialogs use 1.5, spinners 1.6 and toggle groups 1.7 | | libsecret | any | `deb` and `rpm`: SecureStore | | glib-networking | any | `deb` and `rpm`: the desktop's proxy settings | | GStreamer | 1.22 | `deb` and `rpm` | | OpenSSL | 3 | the host links the system's, so `deb` and `rpm` depend on it by library | The host checks for each newer API as it starts and uses an older one where it is missing, so a newer libadwaita changes how a dialog or a spinner is drawn and not whether the app runs. The project's CI builds the host on AlmaLinux 9 for x64 and arm64 on every pull request, and launches it each night on Ubuntu 24.04 and 26.04, Debian 13, and Fedora 44 and 45. A `deb` is made for Debian 13 and Ubuntu 24.04 or later and an `rpm` for Fedora and the RHEL family 9 or later. A Flatpak does not depend on the system's libraries. ## Build the host from source `npm run linux` uses a [prebuilt host](#prebuilt-hosts) when there is one for the app. Otherwise it builds the GTK host from source, which takes longer than a Mac's build and is reused after the first one, in `$XDG_CACHE_HOME/ng-native/desktop` (`~/.cache` when that is not set). Before it starts, the command checks the toolchain and stops with a fix-it line for each problem. It needs: | Tool | Minimum | | -------------------- | -------------------- | | clang and lld | installed | | CMake | 3.25 | | Ninja | 1.10 | | GTK 4 headers | 4.10 | | libadwaita headers | 1.4 | | libsecret headers | 0.20 | | Git, curl, unzip, xz | installed | | Perl with `shasum` | installed | | Python 3, pkg-config | installed | | Pango, GLib, X11 | development packages | | OpenSSL 3, nghttp2 | development packages | | zlib, SQLite | development packages | On Debian and Ubuntu: ```sh sudo apt install clang lld cmake ninja-build git curl unzip xz-utils perl python3 pkg-config \ libgtk-4-dev libadwaita-1-dev libsecret-1-dev libpango1.0-dev libglib2.0-dev libx11-dev \ libssl-dev libnghttp2-dev zlib1g-dev libsqlite3-dev ``` On Fedora, and on RHEL 9 and its rebuilds: ```sh sudo dnf install clang lld cmake ninja-build git curl unzip xz perl perl-Digest-SHA python3 \ pkgconf-pkg-config gtk4-devel libadwaita-devel libsecret-devel pango-devel glib2-devel \ libX11-devel openssl-devel libnghttp2-devel zlib-devel sqlite-devel ``` On RHEL and its rebuilds, Ninja and the GTK and libadwaita headers are in the CRB repository: `sudo dnf config-manager --set-enabled crb` first. The command names the package for apt or dnf by `/etc/os-release`, and both when it cannot read it. ## Test Linux from a Mac Everything an app's tests do on Linux works from a Mac, at three depths. - **In Node.** `render(X, { os: 'linux' })` renders a component as on Linux, with recording fakes of the windows, menus and tray, and the desktop template's `node-linux` project resolves `.linux` files. `npm test` runs it. See [Testing on another OS](/packages/testing/testing-other-os). - **In the real host.** `npx vitest --project linux` runs `src/**/*.device.ts` inside the GTK host, on real GTK widgets. On a Mac the host runs in the AlmaLinux 9 container image `ngn-el9`, under Docker or Colima, which you build once: ```sh docker build -t ngn-el9 node_modules/@ng-native/desktop/native/docker EXPO_PUBLIC_DEVICE_TESTS=1 npx expo start # in one terminal npx vitest --project linux ``` The host binary is the prebuilt one for the Mac's architecture. See [In-app tests](/packages/testing/in-app-tests#what-a-run-does-on-linux). - **A package.** `npm run package -- --os linux` makes the app folder and the `deb` on a Mac with no tools. The `rpm` and the Flatpak run in containers, through Docker or Podman. What the container cannot show is on a real desktop: Orca, Wayland, input methods, fractional scaling and the KDE conventions. The project checks those by hand on an Ubuntu virtual machine before each release. ## Package the app ```sh npm run package -- --os linux # dist/linux: the app folder and .tar.gz npm run package -- --os linux --format deb --maintainer "Ada Lovelace " npm run package -- --os linux --format rpm --license MIT npm run package -- --os linux --format flatpak --license MIT ``` `--os` defaults to the machine's own, so on Linux `npm run package` makes the same. A Linux package is a release build with the JavaScript compiled to Hermes bytecode, one package for each architecture: `--arch x64` or `--arch arm64` makes one, and `--arch all`, the default, both. `--output` puts them somewhere other than `dist/linux`. | Format | Makes | For | | --------- | ------------------------------------------------------ | -------------------------------------------- | | `app` | a runnable folder and its `.tar.gz` | testing, and a download for any distribution | | `deb` | `__.deb` | Debian 13 and Ubuntu 24.04 or later | | `rpm` | `--1..rpm` | Fedora and the RHEL family 9 or later | | `flatpak` | a `.flatpak` for each architecture, and an OSTree repo | the sandboxed route, on the GNOME runtime | A `deb` and an `rpm` use the system's GTK and libadwaita, and are updated by the distribution's package manager from your own repository. A Flatpak runs in a sandbox on the GNOME runtime 50 and is updated from its own remote. `deb` and `app` need nothing but Node. `rpm` runs `rpmbuild` and `flatpak` runs `flatpak-builder`, on Linux when they are installed and otherwise in a container, AlmaLinux 9 for the `rpm` and Fedora 44 for the Flatpak, through Docker or Podman; the command stops first, naming what is missing. A Flatpak for an architecture other than the machine's needs QEMU's binfmt handlers. What the command needs from the app, and stops before building to say what is missing: - **`expo.description`.** Its first sentence is the summary software centres list. - **`ios.bundleIdentifier`**, which is the Linux application id, as it is the Mac's bundle identifier. `deb`, `rpm` and `flatpak` need it; an `app` build makes `dev.ngnative.` when there is none. A Flatpak's id has three to five parts, with a dash only in the last. - **`expo.icon`**, a square PNG, which is scaled into the hicolor sizes up to its own. An app with no icon installs none. - **`--license`**, an SPDX expression such as `MIT`, for an `rpm` and a Flatpak. - **`--maintainer`**, `"Name "`, for a `deb`. - **`--homepage`**, an `https` URL, and **`--categories`**, a list of freedesktop categories with a main one, such as `Utility;Office`. Categories default to `Utility`. Each format installs `.desktop`, whose `MimeType` lists the plugin options' `documentTypes[].mimeTypes` and the app's URL schemes, the icons, and `.metainfo.xml`, built from `name`, `description` and `version` and from `--license` and `--homepage`. A `deb`, an `rpm` and a Flatpak also install a D-Bus service and mark the desktop entry `DBusActivatable=true`, so opening a link or a file starts the app, or hands it to the one that is running (see [Windows](/packages/device/app-windows)). The package name is the slug, and the version is `version`. The plugin options hold nothing for Linux packaging. `capabilities` still applies, and a Flatpak makes each declared path a `--filesystem` permission, and cannot run the system's programs: the command warns about `spawn` and `paths` as it packages. ### Signing Signing keys come from the environment, never from `app.json` or an argument. Set `NGN_GPG_KEY` to the key's id, with the key in the GPG agent or in `GNUPGHOME`: - **`app`** gets a detached, armoured `--.tar.gz.asc` beside the archive. - **`rpm`** is signed with `rpmsign`. - **`flatpak`** has its commits and its repository's summary signed, so the remote can verify them. - **`deb`** carries no signature of its own, since apt checks the repository's: sign the repository. The command stops first when `NGN_GPG_KEY` is set and `gpg` is not installed. Linux has no notarisation, Developer ID, Sparkle or `--feed-url`, and those flags stop the command on Linux. ### Distribute The command makes packages, not repositories. Serve a `deb` or an `rpm` from your own apt or dnf repository, built with the distribution's own tools, and the package manager updates it. For Flatpak, serve the `flatpak-repo` folder it writes over HTTPS as the app's own remote: ```sh flatpak remote-add --if-not-exists my-app https://example.com/repo --gpg-import=key.gpg flatpak install my-app dev.example.MyApp ``` The `.flatpak` bundle installs on its own with `flatpak install ./my-app-1.0.0-x86_64.flatpak`, fetching the runtime from Flathub. A Flatpak made this way is the app's own remote: Flathub does not take an app that ships a prebuilt host without an exception, and the manifest the command writes beside the repository is what a submission would start from. The JavaScript updates in place, from a server you host, as on macOS: see [Over-the-air updates](/guide/ota-updates). A new version of the host itself is a new package. ## Prebuilt hosts Each release of `@ng-native/desktop` publishes a Linux host for x64 and for arm64, in two flavours: the debug host `npm run linux` runs, with React Native's debugger, and the release host `package` ships. Each is built on AlmaLinux 9 and packed with its `hermesc`, and is not signed. A download is checked by the SHA-256 in `prebuilt.json` and deleted if it does not match. The command uses one when the app links no native desktop code of its own, its host libraries (`react-native-screens`, `react-native-safe-area-context`, `react-native-svg`, `react-native-webview`, `react-native-worklets` and `react-native-reanimated`) are the versions the host was built with, and the app denies none the host has. Otherwise it builds from source, for the machine's architecture. A Mac therefore packages for Linux with no Linux machine unless the app has native desktop code of its own, which needs a Linux machine of each architecture it packages for. `NGN_DESKTOP_FROM_SOURCE=1` always builds from source. See [Prebuilt hosts](/packages/desktop/packaging#prebuilt-hosts). ## What differs on Linux [What differs](/guide/desktop-differences) lists what the app sees: the `OS` token, which files a Linux build takes, and the windows and the app. The host's own pages say what each part of an app becomes on GTK: - [Windows, menus and the tray](/packages/desktop/windows-and-menus): the menu bar on KDE Plasma and the header bar's main menu elsewhere, the tray as a StatusNotifierItem, and the badge. - [Focus and accessibility](/packages/desktop/accessibility): Orca, and the structural navigation it does not have. - [Expo modules on the desktop](/packages/desktop/expo-modules): the portals each service uses. - [Sizing for GNOME](/guide/desktop-sizing#sizing-for-gnome). --- # What differs on the desktop ## The OS `OS` from `@ng-native/device` and React Native's `Platform.OS` answer `'macos'`. `DESKTOP` is true on macOS, and `APPLE` on iOS and macOS, so a check for an Apple OS does not have to be written as `OS === 'ios'`. The `macos:` and `desktop:` Tailwind variants and the `platform-macos` class match on a Mac. Linux is an OS too: `OS` answers `'linux'` there, `DESKTOP` is true and `APPLE` false, and the `linux:` and `desktop:` variants match. A Linux build takes `.linux`, then `.ios`, then `.native` files, React Native's iOS code, and `Platform.select` from `linux`, then `ios`, as a Mac build does for `macos`; a `macos` key does not answer on Linux. React Native's types have no `'linux'`, so check `OS` from `@ng-native/device` rather than `Platform.OS`. [On Linux](#on-linux) below says what else differs. ## Which files a Mac build takes An import without an extension resolves `.macos` first, then `.ios`, then `.native`, then the plain file. A library's iOS file is what a Mac build takes where it has no macOS one. React Native's own JavaScript runs its iOS code on a Mac, since the desktop host answers its iOS-named native modules. Inside React Native's `Libraries` and `src`, each `Platform.OS === 'ios'` comparison is rewritten as the bundle is built to match `'macos'` as well. Code outside React Native is left alone. `Platform.select` answers from `macos`, then `ios`, then `native`, then `default`, in every file. ## For library authors Your code sees `Platform.OS === 'macos'`, so a branch written for `'ios'` is not taken on a Mac: ```ts // Taken on iOS only. if (Platform.OS === 'ios') useAppleApi(); // Taken on iOS and macOS. if (Platform.OS === 'ios' || Platform.OS === 'macos') useAppleApi(); // Or let select fall back: on a Mac it reads `macos`, then `ios`. const inset = Platform.select({ ios: 20, android: 0 }); ``` A `.ios.ts` file is used on a Mac unless a `.macos.ts` sits beside it. A library's native code reaches the Mac build through its `expo-module.config.json`: see [Native code](/packages/desktop#native-code). One with iOS or Android code and none for the desktop is listed when the app builds, and its native module is absent on macOS. ## Expo's packages None of Expo ships in a Mac app: `expo-*` packages resolve to an empty module. The services in `@ng-native/expo` with a desktop source answer from the host's own modules (`DESKTOP_MODULES` lists them). A service whose module the host has not got throws `MissingModuleError` on first use, and a mobile-only one, such as sensors or the screen orientation, is absent: its `available()` is false. `import 'expo'` still installs a runtime: `URL`, `URLSearchParams`, `TextDecoderStream`, `structuredClone`, and a `fetch` whose `Response` streams its `body`, over React Native's Networking module. The host streams the body as bytes, so `body`, `bytes()` and `arrayBuffer()` are byte-exact for any content, an image included. `blob()` is made from the body as text, so it is exact only for a text body; read binary data through `arrayBuffer()`. ## Events `(mouseenter)`, `(mouseleave)`, `(mousemove)`, `(mouseover)` and `(mouseout)` are React Native's pointer events, and `(dblclick)`, `(contextmenu)` and `(wheel)` are the desktop host's. They keep their DOM names, as on the web. `@ng-native/eslint-plugin`'s `desktop-only-events` rule warns, in an app that also builds for iOS or Android, that each fires only on a desktop OS. ## Windows and the app - Closing the last window leaves the app running in the Dock, and a click on the Dock icon opens the main window again. `provideAppLifecycle({ quitWhenLastWindowCloses: true })` quits instead. - A window's frame is saved and comes back on the next launch. After a reload or a relaunch the main window, route windows and `restoreKey` windows open again. - Back and forward (Cmd-[ and Cmd-], a swipe, mouse buttons 4 and 5) move through each window's history, as a browser does. Forward builds the page again from its URL, so a page's scroll position and form state are not kept. - A tab app's tabs are the window's sidebar. - `` is a sheet on the window, a cover inside it, or with an `anchor` a popover. ## Not on a Mac `refresh-control`, `input-accessory-view` and `full-window-overlay` are a plain view. `controlSize` sizes the native controls on macOS and `` on iOS, and Android ignores it. ## On Linux The same app on Linux differs from a Mac's in these ways. [Build for Linux](/guide/desktop-linux) has the setup and the packages. - Closing the last window quits the app, and `provideAppLifecycle({ quitWhenLastWindowCloses: false })` keeps it running instead. There is no Dock to click: launching the app again, from the launcher or with a link or a file, goes to the instance running and opens its main window. - A window's size is saved and comes back, maximised or full screen when it was, but never its place: the desktop places each window. After a reload or a relaunch the main window, route windows and `restoreKey` windows open again. - The menu bar is a bar under the header bar on KDE Plasma and the header bar's main menu on every other desktop. `mod` in a shortcut is Ctrl. Back and forward are Alt+Left and Alt+Right, the keyboard's Back and Forward keys, and mouse buttons 8 and 9. - The title bar is libadwaita's header bar, with the window controls in every `titleBar` mode. - A `` is a StatusNotifierItem, shown only where a StatusNotifierWatcher runs (KDE Plasma, and GNOME with the AppIndicator extension): `Tray.available()` is `false` elsewhere. `Dock.available()` is always `false`, and the badge is the launcher's count, which KDE Plasma and Ubuntu's dock show and stock GNOME does not. - Text follows the desktop's text scaling, as `fontScale`, and layout sizes do not. See [Sizing for GNOME](/guide/desktop-sizing#sizing-for-gnome). - Files, links, notifications and printing go through the desktop's [portals](/packages/desktop/portals), and SecureStore needs a Secret Service (GNOME Keyring or KWallet) running. - Orca reads the app and its focus, and has no structural navigation by heading or landmark. See [Focus and accessibility](/packages/desktop/accessibility#on-linux). - A new version of the app's host reaches it as a new package, from the package manager or Flatpak; JavaScript updates come from the app's own Expo Updates server, as on macOS. --- # Sizing for the Mac Nothing rescales an app on macOS. A size in points is the same size in points on every OS: `rem` is 16 points, text with no size is 14 points, and the system text size does not apply. A Mac uses smaller type and denser rows than a phone, so an app gives the Mac its own sizes. ## The Mac's sizes | What | Size | | ------------------------- | ----------- | | Body text | 13 pt | | Captions and secondary | 11 pt | | A list or sidebar row | 22 to 28 pt | | The least a target can be | 20 pt | ## Giving the Mac its own The `macos:` Tailwind variant and the `platform-macos` class on the root match on a Mac only, and `desktop:` on a Mac and on Linux: ```html Inbox ... ``` ```css :host { padding: 16px; } :host-context(.platform-macos) { padding: 20px; } ``` The native controls (``, ``, ``, ``, ``) are AppKit's own, measured at their `controlSize`: `mini`, `small`, `regular` (the default) or `large`. Give them no width or height of your own. The sidebar's rows, the toolbar and the menu bar are drawn by AppKit at the system's sizes. ## Sizing for GNOME On Linux, `rem` is 16 points and text with no size is 14 points too, but text follows the desktop's text scaling: GNOME's Large Text and its text scaling factor set `fontScale`, which text sizes are multiplied by, as Dynamic Type's are on iOS. Layout sizes in points do not scale with it. The least a target can be on Linux is 24 by 24 points, WCAG 2.2's minimum target size. WCAG allows exceptions, such as a smaller target with enough space around it. The `linux:` Tailwind variant and the `platform-linux` class match on Linux only, and `desktop:` matches on macOS and Linux: ```html Inbox ``` The native controls are GTK's and libadwaita's, measured as GTK lays them out at the desktop's own sizes; `controlSize` does nothing there. Give them no width or height of your own. The header bar, its buttons and the window controls are libadwaita's, at its sizes. --- # Where desktop APIs come from | API | Import from | | ------------------------------------------------------------------------------- | ------------------------------------ | | `AppWindows`, `CURRENT_WINDOW`, `provideMainWindow`, `provideRestorableWindows` | `@ng-native/device` | | `AppLifecycle`, `provideAppLifecycle` | `@ng-native/device` | | `Menus`, `Dock`, `Tray`, `UndoStack` | `@ng-native/device` | | `Processes`, `Shell` | `@ng-native/device` | | `OS`, `OS_VERSION`, `DESKTOP`, `APPLE` | `@ng-native/device` | | `Dialogs`, `DeepLinks`, `Screen`, `SafeArea` | `@ng-native/device` | | `MenuBar`, `MenuGroup`, `MenuItem`, `MenuSeparator`, `ContextMenu` | `@ng-native/components` | | `Shortcut`, `TrayIcon`, `NativeButton` | `@ng-native/components` | | `FileDrop`, `DragItem` | `@ng-native/components` | | `SplitView`, `Sidebar`, `SidebarSection`, `SidebarItem` | `@ng-native/components` | | `NavigationHistory`, `SidebarItemPath` | `@ng-native/router` | | `DocumentPicker` | `@ng-native/expo/document-picker` | | `Printing` | `@ng-native/expo/printing` | | `Clipboard` | `@ng-native/expo/clipboard` | | `Haptics` | `@ng-native/expo/haptics` | | `KeepAwake` | `@ng-native/expo/keep-awake` | | `SecureStorage` | `@ng-native/expo/secure-store` | | `fakeWindows`, `fakeMenus`, `fakeDock`, `fakeTray`, `fakeProcesses`, `fakeUndo` | `@ng-native/testing` | | `provideDesktopFakes`, `fakeDeepLinks` | `@ng-native/testing` | | The `ng-native-desktop` command and the config plugin | `@ng-native/desktop`, never imported | An element is used by its selector once its class is in the component's `imports`: `MenuBar` is ``, `ContextMenu` is `[contextMenu]`, `Shortcut` is `[shortcut]`, `FileDrop` is `(fileDrop)`, `DragItem` is `[dragItem]`, `SplitView` is ``, and `SidebarItemPath` is ``. --- # What each OS has The APIs and inputs that macOS brought, and what each does on every OS. A test holds this table to the code: it names every desktop API and every macOS-only input, and each service's `available()` follows its row. - **yes** - it works as on macOS. - **absent** - the service's `available()` is `false`, and every call does nothing and answers its empty value: `[]`, `null`, `false` or nothing. - **ignored** - the input has no effect. - **inert** - the element draws nothing. - Anything else says what the OS does in its place. Each service's own page says the same for that service. The services from `@ng-native/expo` work on macOS through the desktop host where their pages say so. --- # Coming from Electron An Electron app is a web page in a browser window, with a Node.js main process beside it. An Angular Native desktop app is native views, AppKit's on a Mac and GTK's on Linux, run by one JavaScript runtime. There is no main process and no renderer process, so there is no IPC: every window is part of the one Angular app, and a root service is shared by all of them. Linux works the same way, and the rows below say where it differs. Windows is planned, with no date. | Electron | Angular Native | | ---------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------- | | `new BrowserWindow()` | `AppWindows.open(Component, options)` or `AppWindows.open({ outlet, path })` | | The first window | The root component, in the main window; `provideMainWindow` sizes it | | `ipcMain`, `ipcRenderer`, `contextBridge` | None: inject a root service in each window | | `win.on('close')` with `preventDefault()` | `window.canClose(guard)`, on the handle or on `CURRENT_WINDOW` | | `app.on('window-all-closed')` | `provideAppLifecycle({ quitWhenLastWindowCloses })`, false on macOS by default, true on Linux | | `app.on('before-quit')` | `AppLifecycle.willQuit(handler)` | | `app.quit()` | `AppWindows.quit()` | | `app.on('activate')` | Handled: a Dock click with no window open opens the main window | | `app.on('open-url')` | `DeepLinks`, for the app's url schemes | | `app.requestSingleInstanceLock()` | None: opening the app brings it forward, though `open -n` starts another; on Linux a second launch goes to the running one | | `Menu.setApplicationMenu()` | `` with `` and `` | | `Menu.popup()` for a context menu | `[contextMenu]` with a template of ``s | | An accelerator on a menu item | `shortcut="mod+s"` on ``, or `[shortcut]` on any element | | `globalShortcut` | None: a shortcut works while the app is in front | | `new Tray()` | ``; on Linux a StatusNotifierItem, where a watcher runs | | `app.dock.setMenu()`, `app.dock.bounce()` | `Dock.setMenu()`, `Dock.bounce()`; Linux has no Dock | | `dialog.showOpenDialog()` | `DocumentPicker.pick()` or `DocumentPicker.pickDirectory()` | | `dialog.showSaveDialog()` | `DocumentPicker.save()` | | `dialog.showMessageBox()` | `Dialogs.tell()`, `Dialogs.confirm()` or `Dialogs.ask()` | | `shell.openExternal()` | `Shell.openExternal()` | | `shell.openPath()`, `shell.showItemInFolder()` | `Shell.openPath()`, `Shell.showItemInFolder()` | | `child_process.spawn()` | `Processes.spawn()`, for the programs the plugin options declare | | `process.env` | `Processes.env`, the variables the plugin options declare | | `clipboard` | `Clipboard` | | `autoUpdater` | Sparkle, embedded by `npm run package -- --format dmg --feed-url `; on Linux, the package manager or Flatpak | | `electron-builder`, notarisation | `npm run package -- --format dmg`, signed, notarised and stapled; on Linux `--os linux --format deb`, `rpm`, `flatpak` or `app` | ## Node's APIs There is no Node.js in the app. A program runs only when the `capabilities` in the plugin options declare it, with the arguments they allow, and never through a shell. See [Processes and Shell](/packages/device/processes). ## The web page A template is native elements (``, ``, ``), styled with CSS that the engine resolves into native props, not HTML in a browser. `:hover`, `:focus-visible`, `cursor` and the mouse events work on a Mac and on Linux. See [What differs on the desktop](/guide/desktop-differences). --- # Package in GitHub Actions EAS Build does not build macOS apps, so a Mac app is packaged on a Mac. GitHub's macOS runners have Xcode, which packaging needs for the app icon. `npm run package -- --format dmg` signs the app with your Developer ID, notarises it, staples it, and writes `dist/macos/.dmg`. ## What it needs - A **Developer ID Application** certificate, exported from Keychain Access as a `.p12` with a password. - An **App Store Connect API key** for notarising: its `.p8` file, its key id and its issuer id. - `ios.bundleIdentifier` set in `app.json`. Add these as repository secrets: | Secret | What it holds | | ----------------------- | -------------------------------------------------------- | | `MACOS_CERTIFICATE` | The `.p12`, base64-encoded (`base64 -i certificate.p12`) | | `MACOS_CERTIFICATE_PWD` | The `.p12`'s password | | `MACOS_SIGN_IDENTITY` | `Developer ID Application: Your Name (TEAMID)` | | `APPLE_API_KEY_P8` | The `.p8` file's contents | | `APPLE_API_KEY_ID` | The key's id | | `APPLE_API_ISSUER` | The issuer id | ## The workflow ```yaml name: Package for macOS on: push: branches: [main] jobs: dmg: runs-on: macos-15 steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 with: node-version: 22 cache: npm - run: brew install ninja - run: npm ci - name: Import the signing certificate env: MACOS_CERTIFICATE: ${{ secrets.MACOS_CERTIFICATE }} MACOS_CERTIFICATE_PWD: ${{ secrets.MACOS_CERTIFICATE_PWD }} run: | echo "$MACOS_CERTIFICATE" | base64 --decode > certificate.p12 security create-keychain -p ci build.keychain security default-keychain -s build.keychain security unlock-keychain -p ci build.keychain security import certificate.p12 -k build.keychain -P "$MACOS_CERTIFICATE_PWD" -T /usr/bin/codesign security set-key-partition-list -S apple-tool:,apple: -s -k ci build.keychain rm certificate.p12 - name: Package env: NGN_SIGN_IDENTITY: ${{ secrets.MACOS_SIGN_IDENTITY }} APPLE_API_KEY_ID: ${{ secrets.APPLE_API_KEY_ID }} APPLE_API_ISSUER: ${{ secrets.APPLE_API_ISSUER }} APPLE_API_KEY_P8: ${{ secrets.APPLE_API_KEY_P8 }} run: | echo "$APPLE_API_KEY_P8" > "$RUNNER_TEMP/AuthKey.p8" APPLE_API_KEY="$RUNNER_TEMP/AuthKey.p8" npm run package -- --format dmg - uses: actions/upload-artifact@v4 with: name: macos-dmg path: dist/macos/*.dmg ``` `APPLE_API_KEY` is the path to the `.p8` file, which `notarytool` reads. The command checks every credential before it builds anything, and names any that is missing. A notarisation Apple rejects stops it with the submission's id, for `xcrun notarytool log ` with the same key. The first package downloads the prebuilt release desktop host when `@ng-native/desktop` has one for the app's React Native version and the app links no native desktop code of its own. Otherwise it builds the host from source, which needs CMake and Ninja (the `brew install ninja` step) and takes a few minutes. Either way the host goes into `~/Library/Caches/ng-native/desktop`, which `actions/cache` can keep between runs. ## Updates To have the app update itself, pass `--feed-url` with your Sparkle appcast's url, and set `NGN_SPARKLE_PUBLIC_KEY` to Sparkle's public EdDSA key from a secret: the app embeds Sparkle, and the `.zip` it updates from is written beside the `.dmg`, for you to upload with the appcast. See [Package the app](/packages/desktop#package-the-app). --- # Deployment [Getting started](/guide/getting-started) uses Expo Go, which covers most development. To include your own native code, build an app for a physical device and eventual App Store or Google Play distribution. - A **development build** includes Expo's launcher, fast refresh and dev menu. Use it for native modules or dependency patches absent from Expo Go. - A **preview build** compiles in release mode for device testing without store submission. - A **release build** is ready for submission: minified, without dev tools or Angular dev-mode assertions. See "What a release build strips" below. ## Configure the app All builds read `app.json`. The template supports Expo Go; native builds also need reverse-DNS iOS bundle and Android package identifiers. Both become permanent after shipping: ```json { "expo": { "name": "My App", "slug": "my-app", "version": "1.0.0", "ios": { "bundleIdentifier": "com.example.myapp" }, "android": { "package": "com.example.myapp" } } } ``` `version` is the store's human-readable version. iOS build numbers and Android version codes are separate build-time values. EAS Build increments them when a profile sets `autoIncrement`. The template has no `android/` or `ios/` folder. `npx expo run:ios`, `npx expo run:android` and EAS Build generate native projects from `app.json` using `expo prebuild` before compiling. Config changes take effect on the next build without manual syncing. ## Install `expo-dev-client` for a development build Install the package required for development builds, beyond Expo Go: ```sh npx expo install expo-dev-client ``` ## Build ### Locally ```sh npx expo run:ios npx expo run:android ``` These commands require Xcode or Android Studio, compile development builds locally and install on a connected device or simulator. Add `--configuration Release` (iOS) or `--variant release` (Android) for a local release build with no dev tools or Metro connection, the closest thing locally to what a store submission runs. ### With EAS Build ```sh npm install -g eas-cli eas login eas build:configure ``` `eas build:configure` writes `eas.json`, with three profiles: ```json { "build": { "development": { "developmentClient": true, "distribution": "internal" }, "preview": { "distribution": "internal" }, "production": { "autoIncrement": true } } } ``` `distribution: "internal"` permits direct-link installation without a store or a paid Apple developer account for testing. `developmentClient: true` installs `expo-dev-client` and enables Metro. Omit it for `preview` and `production` release builds. `autoIncrement` increases the build number and version code per build to prevent duplicate submissions. ```sh eas build --platform ios --profile development eas build --platform android --profile preview ``` EAS Build uses Expo's machines by default. `--local` produces the same artifact locally and requires the native toolchain used by `expo run`. Use it when Expo's build servers are unreachable or policy prohibits sending source off the machine. ### Signing On the first platform build, cloud builds create and store an Apple distribution certificate and provisioning profile or an Android upload keystore, then reuse them. Manage them with `eas credentials`. Local builds use the machine's Xcode or Android Studio signing configuration. ## Installing on a device Install **internal** development or preview builds through their device link or [Expo Orbit](https://expo.dev/orbit), which also installs from the build page. iOS devices must be registered to the signing Apple developer account; add them with `eas device:create`. Android APKs install on any device that permits them. Submit **production** builds, then use TestFlight or the Play Console's internal testing track to install them before public release. ## Submit to a store ```sh eas submit --platform ios eas submit --platform android ``` These commands submit the profile's latest build by default; use `--path` for another binary. iOS requires an App Store Connect API key or Apple ID and uploads to App Store Connect, appearing in TestFlight in ten to fifteen minutes. Android requires a Google Play service account key and uploads to the track selected in `eas.json` or on the command line. For screenshots, review information and first submissions, see Expo's guides: [Submit to the Apple App Store](https://docs.expo.dev/submit/ios/) and [Submit to the Google Play Store](https://docs.expo.dev/submit/android/). ## macOS EAS Build does not build macOS apps. A Mac app is a release build packaged on a Mac by the [desktop host](/packages/desktop)'s command, universal for Apple silicon and Intel Macs, for macOS 14 and later: ```sh npm run package # dist/macos/.app, signed ad hoc, for this Mac npm run package -- --format dmg # Developer ID signed, notarised and stapled, to download npm run package -- --format mas # a sandboxed installer package for App Store Connect ``` Packaging needs full Xcode, which compiles the app icon. A `dmg` or `mas` needs `ios.bundleIdentifier`, and takes its signing identity, notary credentials and provisioning profile from environment variables, never from `app.json`. [Package the app](/packages/desktop#package-the-app) lists them, and [Package in GitHub Actions](/guide/desktop-github-actions) builds, signs and notarises on every push. `eas submit` has no macOS target: upload a `mas` package with Apple's Transporter app. ## What a release build strips The Metro preset replaces `ngDevMode` with `false` in minified bundles, including release and preview builds. The minifier removes Angular's dev-mode assertions, error strings and `setClassMetadata` calls as dead code. See [Metro](/packages/metro) for other build-time processing. Development builds remain unminified, larger and slower. --- # OTA updates An over-the-air (OTA) update replaces the JavaScript bundle and the assets of an installed app without a new store build. Native code stays as it was built, so an update can change anything the Metro bundle holds: Angular code, templates, styles and images. A change to a native module, a config plugin or `app.json` still needs a store release. Two services do this in an NG Native app. Both need `expo prebuild` and a build of your own. Expo Go cannot run either: it has no HotCodePush module, and it keeps `expo-updates` for loading projects, with its update API disabled. A development build can preview an EAS update. Pick one service: the HotCodePush prebuild refuses an app with `expo-updates` enabled, because each decides which bundle the app runs. ## expo-updates Expo's own module, served by [EAS Update](https://docs.expo.dev/eas-update/introduction/) or a server you host. The [Updates](/packages/expo/updates) service wraps it: `check()` downloads an update and `apply()` restarts the app into it. That page covers the install and the service's state. ## On macOS and Linux EAS Update does not update desktop apps. A packaged Mac or Linux app takes Expo Updates (protocol 1) from a server you host, at the `updates.url` in `app.json`: the desktop host downloads the launch asset and the update's other assets, checks each against the manifest's hash, and, with `updates.codeSigningCertificate` set, checks the manifest's signature. An update whose launch crashes before it has shown its first frame for 10 seconds (or been quit cleanly once its bundle has loaded) is not run again, so a quit while the bundle is still loading counts as a failed launch; once it has, a later crash does not roll it back, and an update downloaded before the app itself was updated (by Sparkle, a package manager or Flatpak) does not run over the new version's bundle. The [Updates](/packages/expo/updates) service is the same on the desktop: `check()` and `apply()`, with `enabled` false in development and without an `updates.url`. The host asks the server with `expo-platform` set to `macos` or `linux`. A Linux app keeps its updates in `$XDG_DATA_HOME//updates`, outside the install folder, which a `deb`, `rpm` or Flatpak installs read-only; the package manager or Flatpak still updates the app itself. A `dmg` packaged with `--feed-url` also embeds Sparkle, which replaces the whole app, native code included, rather than its bundle: see [A new version of the whole app](/packages/expo/updates#a-new-version-of-the-whole-app). ## HotCodePush HotCodePush, the over-the-air (OTA) update service for React Native, Expo, Capacitor and Cordova, ships its Expo SDK as a config plugin. The plugin wires the native projects at prebuild and the CLI bundles and uploads the platform you name. An NG Native app needs no change to the SDK: its JavaScript API is plain functions, and the plugin edits the files `expo prebuild` writes. ### Install ```sh npm install @hotcodepush/expo-ota-updates @ng-native/expo npm install --save-dev hotcodepush ``` `@ng-native/expo` loads the SDK in a service below. Install it at the version of your other `@ng-native` packages, and before the build: it carries native modules, a native module changes the build's fingerprint, and an update only reaches the builds whose fingerprint it was made for. Add the plugin after `@ng-native/metro`: ```json { "expo": { "plugins": ["@ng-native/metro", "@hotcodepush/expo-ota-updates"] } } ``` Add a `hotcodepush.json` next to `app.json`, with the app id from the [console](https://console.hotcodepush.com) and the channel this build follows: ```json { "appId": "4f2b7c9e-8d31-4a6e-9b0f-2c5d7e8a1b34", "channel": "production" } ``` Then sign in with `npx hotcodepush login`, or set `HOTCODEPUSH_TOKEN` in CI. A release build runs the CLI, which registers the build and uploads the bundle it embeds, so later updates download only the files that changed. Signed out, a local build only warns and registers nothing, while a CI build fails. Generate a signing key with `npx hotcodepush signing-key create`. It adds the public key to `hotcodepush.json`, the build embeds it, and from then on the app runs only bundles signed with the private key. Without a key the app trusts whatever the HotCodePush servers deliver. The private key lands in `hotcodepush-private-key.pem` in the working directory. Add that file to `.gitignore` before the next commit and keep it where your CI secrets live, since whoever holds it can sign the app's updates. `npx hotcodepush init` does all of this in one step: it installs the package, writes the file, adds the plugin entry, signs you in and offers to generate the key. Then build in release, since a debug build takes its JavaScript from Metro and no update: ```sh npx expo prebuild npx expo run:ios --configuration Release npx expo run:android --variant release ``` ### Call it from a service The SDK exports `HotCodePush`, an object of promise-returning functions with no React in its API. Load it the way [a module with no service](/packages/expo/using-a-module#a-module-with-no-service) is loaded, through a token whose factory calls `expoModule()`, so the service is inert in a test in Node and a test can provide a stand-in: ```ts import { InjectionToken, Service, inject, signal } from '@angular/core'; import { expoModule } from '@ng-native/expo'; interface NativeHotCodePush { sync(): Promise<{ status: string }>; } export const HOT_CODE_PUSH = new InjectionToken('app.hotCodePush', { factory: () => expoModule( '@hotcodepush/expo-ota-updates', () => (require('@hotcodepush/expo-ota-updates') as { HotCodePush: NativeHotCodePush }) .HotCodePush, ), }); @Service() export class OtaSync { private readonly native = inject(HOT_CODE_PUSH); readonly lastStatus = signal(null); async sync(): Promise { const result = await this.native?.sync(); this.lastStatus.set(result?.status ?? null); } } ``` The package's own `SyncResult` type describes the full result, if you import it. `sync()` runs one cycle, check, download and apply, and resolves a typed result. With the defaults the SDK runs the same cycle on its own at every start, downloads in the background and applies the update at the start after that, so the app never restarts under the user's hands. A release marked mandatory is the exception: by default it applies as soon as it downloads, which restarts the app and discards unsaved state such as a half-filled form. Set `mandatoryApplyStrategy` to `manual` in `hotcodepush.json` to apply it yourself at a safe moment. A rollback guard watches the first start of every update: an update whose bundle does not render in time is rolled back to the one before it. ### Release Change something, then release it to the channel, once per platform. The CLI bundles the platform you name with `expo export:embed`, through the app's own Metro config, so the Angular compilation runs as in a build, and signs the bundle with the private key: ```sh npx hotcodepush release create --platform ios --private-key-path hotcodepush-private-key.pem npx hotcodepush release create --platform android --private-key-path hotcodepush-private-key.pem ``` In CI, put the key's text in `HOTCODEPUSH_SIGNING_KEY`, drop the flag and add `--yes`, since nothing can answer the confirmation there. An app without a registered key releases without the key. The installed app downloads the release at its next start and runs it from the start after that. The [Expo SDK docs](https://hotcodepush.com/docs/sdks/expo) cover the configuration, the API and the events. The [demo app](https://github.com/hotcodepush-team/ng-native-ota-updates-demo) is the template app with the SDK wired in, built on both platforms in CI. --- # Updating an app Every `@ng-native/*` package is released together, at one version. When a release changes something an app has to change too, such as an import path, it ships a **migration** that makes the change for you. The migrations live in `@ng-native/migrate`, and all three ways to update run the same ones: | The app is in | Update with | | -------------------------- | --------------------------------- | | An Nx workspace | `nx migrate @ng-native/nx@latest` | | An Angular CLI workspace | `ng update @ng-native/schematics` | | A plain Expo app (or both) | `npx @ng-native/migrate@latest` | Start from a clean git working tree, so `git diff` shows exactly what the update changed. ## A plain Expo app An app made with `create-expo-app --template @ng-native/template` has neither Nx nor the Angular CLI. Run the migrations with `npx`, before installing the new versions: ```sh npx @ng-native/migrate@latest npm install ``` It reads the `@ng-native/*` version the app's `package.json` lists, runs every migration newer than that version, oldest first, and moves the `@ng-native/*` versions in `package.json` to the new release. It prints each migration it runs, each file it changed (`UPDATE`), and anything left for you to do (`NOTE`). Run the install it names afterwards. ```sh npx @ng-native/migrate@latest --dry-run # print what would change, write nothing npx @ng-native/migrate@latest --from 0.2.0 # the version the app was on npx @ng-native/migrate@latest apps/mobile # an app in another directory ``` If the new versions are already installed, `package.json` already lists them, and the command finds nothing to migrate. Pass the version the app was on with `--from` to run the migrations since then. ## An Nx workspace ```sh nx migrate @ng-native/nx@latest pnpm install nx migrate --run-migrations pnpm install ``` The first command moves every `@ng-native/*` package in the root `package.json` and writes the migrations the update crosses into `migrations.json`, without changing any code yet, so you can read the list first. `--run-migrations` runs them and prints what is left to do as next steps. See [Nx](/packages/nx) for the workspace setup. ## An Angular CLI workspace ```sh ng update @ng-native/schematics ``` `ng update` moves every `@ng-native/*` package in the root `package.json`, installs them, and runs the migrations the update crosses. What is left to do is printed as a warning. To run the migrations again for an update already installed, name the versions: ```sh ng update @ng-native/schematics --migrate-only --from 0.2.0 --to 0.3.0 ``` See [Angular CLI](/packages/schematics) for the workspace setup. ## What the migrations do | Migration | Runs on | What it changes | | ----------------------------------- | ------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `sync-app-versions` | Every update | Moves the `@ng-native/*` versions in every `package.json` in the workspace, an app's own included, to the new release. A `^` or `~` stays; a `workspace:` or `file:` link and a peer range are left alone. | | `split-store-and-player` | Updating to 0.3.0 | Imports `Storage` from `@ng-native/expo/async-storage`, `SecureStorage` from `@ng-native/expo/secure-store`, `audioPlayer` from `@ng-native/expo/audio` and `videoPlayer` from `@ng-native/expo/video`, which used to come from `@ng-native/expo/store` and `@ng-native/expo/player`. A namespace import, `export *`, `require()`, `import()` or a test's `vi.mock` of the old entry point is left as it was, with a note. | | `engine-node-tag` | Updating to 0.14.0 | Reads an engine node's element tag as `tag`, which was `name`, on `EngineNode`, `StyleTarget`, `ViewNameNode` and `NamedHostNode` from `@ng-native/fabric` and `BrowserNode` from `@ng-native/web`. A `.name` is rewritten only where the code shows what it is read from is one of those: a name typed as one, a node's `parent` or `children`, or the `nativeElement` of an `ElementRef`. Each other `nativeElement.name`, each `name` read from a node cast to another type (`node as { name?: string }`, which still compiles), and each `.name` it cannot place in a file that imports one of those types, is left as it was, with a note. | | `engine-node-fields` | Updating to 0.17.0 | Reads an engine node's `children`, `text`, `kind`, `host` and `sheet` as `childList`, `nodeText`, `nodeKind`, `engine` and `templateSheet`, on `EngineNode`, `HostNode`, `StyleTarget` and `ViewNameNode` from `@ng-native/fabric` and `BrowserNode` from `@ng-native/web`. A read is rewritten only where the code shows what it is read from is one of those, as for `engine-node-tag`. Each other read from a `nativeElement`, each read from a node cast to another type, and each it cannot place in a file that imports one of those types, is left as it was, with a note. A node's `props` keep their names, `props['text']` included, and are left alone. | | `library-typecheck-declaration-map` | Updating to 0.17.1 | Sets `declarationMap` to `false` in each `tsconfig.typecheck.json` that `@ng-native/nx:library` wrote (one that extends the library's `tsconfig.lib.json` and has Angular compiler options; an app's is left alone), where Nx's TypeScript preset turns declaration maps on and `ngc` stopped with TS5069. A config that sets `declarationMap` itself is left as it is, and one with comments is left with a note. | | `native-typecheck-target` | Updating to 0.17.1 | Gives each Angular Native project in `angular.json` a `typecheck` target, which `ng run :typecheck` runs: `ngc` on the project's code and templates, after loading its Metro config. A project with a `typecheck` target of its own keeps it. An `angular.json` with comments or trailing commas is left as it is, with a note saying what to add. Nx and plain Expo apps, which have no `angular.json`, are left alone. | | `stop-watching-conditions` | Updating to 0.17.2 | Keeps what `watchConditions(app.engine)` returns in each file that imports it from `@ng-native/device`, as `const stopWatching = watchConditions(app.engine);`, and stops it as the app is destroyed with `app.applicationRef.onDestroy(stopWatching)`. Only a call that is a statement of its own and reads its engine off a named app is rewritten. One given an engine some other way (`watchConditions(engine)`, `this.engine`), or in a file that already has a `stopWatching`, is left as it was, with a note. | | `vitest-tsconfig-paths` | Updating to 0.18.1 | In each `vitest.config.mts` that runs `ngNative()` and imports `nxViteTsPaths` from `@nx/vite`, as `@ng-native/nx` wrote it in a workspace with tsconfig path aliases, imports `tsconfigPaths` from `vite-tsconfig-paths` in its place, since from Nx 24 `nxViteTsPaths` is a stub that resolves nothing and a test importing a library fails with `Cannot find package`. Where the root `package.json` lists Vite 8 or later (or no Vite) and any Vitest it lists is 4.1 or later, sets Vite's `resolve.tsconfigPaths` instead, with no import, and adds `vite` when it lists none; a config with its own `resolve` key keeps the plugin. Adds `vite-tsconfig-paths` to the root `package.json` when it lists none and a config uses it. Another Vitest config is left as it is. | | `os-comparisons-on-macos` | Updating to 0.23.0 | Changes nothing, and notes the comparisons to check on a Mac that it recognises now that the `OS` token, `Platform.OS` and `nativePlatform()` report macOS as `'macos'`, with its file and line: an `=== 'ios'` or `!== 'ios'`, which a Mac used to pass as iOS and now answers the other way, an `!== 'android'`, which a Mac passes as it did before, into a branch that may be written for iOS, and `OS_VERSION` compared directly with a number, which is the macOS major on a Mac. The OS may be quoted with `'`, `"` or a backtick, on either side. A check written another way, such as against a constant that holds `'ios'` or with `OS_VERSION` in brackets, is not noted and needs checking by hand. It reads the app's TypeScript, JavaScript, templates and each component's inline `template`; installed packages are left alone. | | `available-signal` | Updating to 0.23.0 | Calls each service's `available`, now a `Signal` on every service: `haptics.available` becomes `haptics.available()` for `DevMenu`, `Haptics`, `SplashScreen` (and `splashScreen`), `Tracking`, `Fonts` and `Watch`, in code and in the component's template, and `await biometrics.available()` becomes `biometrics.available()` for `Biometrics`, `AppleSignIn`, `ScreenCapture` and `StoreReview`. It follows `haptics['available']` as it follows `haptics.available`. It notes, with file and line, each await it removed, since the signal reads `false` until the platform answers, a call still used as a promise, such as `.then()` or one in `Promise.all`, and a sensor's `available()` compared with `null`, which it never is now. | | `os-comparisons-on-linux` | Updating to 0.24.0 | Changes nothing, and notes the comparisons to check on Linux, now that the `OS` token and `Platform.OS` can answer `'linux'`, with its file and line: an `=== 'ios'` or `!== 'ios'`, which Linux answers as an OS that is not iOS though it takes React Native's iOS code, an `=== 'macos'` or `!== 'macos'`, where a check meant as "a desktop OS" wants `DESKTOP`, and an `!== 'android'`, which Linux passes into a branch that may be written for iOS. The OS may be quoted with `'`, `"` or a backtick, on either side. It reads the app's TypeScript, JavaScript, templates and each component's inline `template`; installed packages are left alone. | A migration changes only what it can change safely. Where it finds something it cannot rewrite on its own, it leaves the file as it was and prints a note saying which file and line to change, and how. A migration that runs a second time changes nothing. ## What is left to do by hand - **Install.** Run the install the update prints, so the new versions are in `node_modules`. - **The notes.** Make each change a `NOTE` line or a printed next step asks for. - **Rebuild the native app** when the update adds or moves a native module: a development build and Expo Go carry only the native modules they were built with. See [Deployment](/guide/deployment). - **Read the changelog** for the release, on the [releases page](https://github.com/ng-native/ng-native/releases), for changes no migration covers. --- # Architecture Angular components call `Renderer2` rather than manipulating nodes. `@angular/platform-browser` implements that interface with calls such as `document.createElement`; `@angular/core` requires no DOM. `@ng-native/platform` provides a `Renderer2` and a `RendererFactory2` that build a retained tree for React Native's Fabric renderer. Fabric turns it into `UIView`s and Android `View`s. Angular replaces React's JavaScript and drives the same C++ renderer, with no React element tree, reconciler or `react-dom` equivalent. ## Rendering packages and responsibilities ``` @ng-native/components one component per native view, plus the behaviour composed into them @ng-native/platform Renderer2 over the engine, and bootstrap @ng-native/fabric the engine: retained tree, commit, events, CSS ``` The engine has no Angular dependency: `@nx/enforce-module-boundaries` bans `@angular/*` imports in `@ng-native/fabric`, catching dependencies the tests would miss. It also has no dependency on React Native's JavaScript; the host supplies what it needs. `@ng-native/platform` contains the only Angular-aware renderer code, fulfilling the role of `@angular/platform-browser` for the DOM. ## What a commit is The engine holds a **retained tree** of elements, text and anchors. Anchors participate in sibling ordering but never reach Fabric. Angular's structural directives use them as placeholders for absent views. The engine records Angular's individual renderer calls to create elements, set props and move children, then commits at most once per change-detection pass. Commits are incremental: unchanged subtrees return to Fabric by reference, avoiding rebuilds that would impair scrolling. Each commit ends with one call to Fabric's `completeRoot`, which diffs the new root against the screen in C++, off the JavaScript thread. ## The host seam Two hosts share an explicit contract. `HostEngine` and `HostNode`, in `@ng-native/fabric`, define only the calls the shared packages make. Fabric's `Engine` implements the former and `EngineNode` extends the latter, preserving the native path. `@ng-native/web`'s `BrowserEngine` implements both over the DOM without casts. `worklet-style`, `worklet-scroll` and `native-gesture` sit outside this interface. They inject the concrete `Engine` to access Fabric handles for Reanimated and react-native-gesture-handler, rather than answer wrongly through a browser stub. A browser build never reaches them: it resolves `@ng-native/components/reanimated` and `/gestures` to inert directives that inject nothing. ## CSS Angular components declare CSS in `styles` and `styleUrl`. Native has no CSS engine, and only `platform-browser` provides the `SHARED_STYLES_HOST` that receives Angular's `styles`. Without its own engine, Angular Native would silently drop component stylesheets. Angular Native handles CSS at build time and runtime. **At build time**, lightningcss parses component stylesheets inside the Metro transform. It converts values for React Native, compiles selectors into compounds and combinators, and sorts rules by specificity then source order. The device does no sorting. The rule set attaches to the component class as a static, which also scopes it: `RendererFactory2.createRenderer(host, type)` receives the component definition, whose class reference lets the renderer find its stylesheet without a registry or generated ID. There is no runtime CSS parser: lightningcss is a native Node addon. **At runtime**, `packages/fabric/src/css.ts` matches and merges rules. It matches right-to-left so the rightmost compound rejects most candidates immediately. Precedence, weakest first: native defaults, matched CSS, explicit props, inline `[style]`, `!important`. The cascade emulates inheritance for `color`, `font*`, `lineHeight`, `letterSpacing`, `textAlign`, `textTransform` and `textDecorationLine`. React Native does not inherit text properties: a view's `color` does not affect its text children. Without this propagation, browser-style sheets would silently lose inherited colors. ## The scope rule **If React Native can express it, CSS gets a spelling for it. If it cannot, the build drops it and warns.** `elevation` compiles because React Native accepts it, even though it has no effect on iOS; no-oping on one platform is React Native's own semantics. `float` has no native equivalent, so it is dropped with a build warning naming the file, the line and the reason; dropping it without a word would hide the problem. `::before`, `::after` and table layout are permanently unsupported - their warnings say so rather than "not yet". React Native's style API cannot express them. A pseudo-element, for example, requires a node absent from the template, making the rendered tree diverge from the code. Declare the element in the template instead. ## Events Fabric dispatches events by node tag. The engine keeps the handler table, runs React Native's responder negotiation (capture down, bubble up, one node holding the gesture), and calls Angular. It uses React Native's event system without adding a synthetic layer. ## Routing `@angular/router` owns URLs, guards, resolvers and lazy loading. `` renders each activated route into an `RNSScreen` from react-native-screens. Pushes use native transitions and back gestures. Screens below the top stay mounted, preserving scroll positions and text-field state. Push, sheet and full-screen modal presentation travel as navigation state, keeping URLs typable, shareable and deep-linkable. --- # Native and web The same components use a shared renderer interface on native platforms and in browsers. Every example on this site runs a real `@ng-native/components` component through the browser renderer, not a screenshot or a React port. Controls have one implementation: `packages/components/src/switch.ts`, for example, serves both hosts. ## The seam `HostEngine` and `HostNode` in `@ng-native/fabric` define only the renderer calls `@ng-native/components` uses. Direct dependencies on `inject(Engine)`, whose constructor requires a `FabricUIManager`, and Fabric's `EngineNode` would couple components to native rendering. Casting a browser object through `as unknown as Engine` would bypass type checking. Fabric's `Engine` implements `HostEngine`; `EngineNode` extends `HostNode`. `BrowserEngine` implements both over the DOM without casts, while the native path stays unchanged. ## Mounting on the web ```ts import { provideRouter } from '@angular/router'; import { mount } from '@ng-native/web'; import { App } from './app/app.ts'; const root = document.getElementById('app-root')!; mount(root, App, { providers: [provideRouter(routes)] }); ``` Browser `mount` differs from `@ng-native/platform`'s `mount` only in host requirements. The first argument is the target `Element`. Fabric instead uses the numeric root tag supplied by React Native's host. The browser needs no `FabricUIManager`, `processColor` or device tokens. It provides `HostEngine`, not `Engine`. `@ng-native/components/reanimated` and `/gestures` need neither on the web: a browser build resolves them to inert directives that need no engine. `DOCUMENT` is the real document, rather than native `mount`'s `TransferState` stub. ## The layout reset Browser and Yoga layout defaults differ. `flex-row` on a `` sets `flex-direction` explicitly and behaves identically on both platforms. Without flex properties, Yoga defaults to `display: flex; flex-direction: column; align-items: stretch; flex-shrink: 0`, while browsers give the unknown `` element `display: inline; flex-shrink: 1`. `@ng-native/web`'s `reset.css` aligns those defaults using `[data-rn]`, which marks every created node. Tag selectors would miss `text-input` and `switch`, rendered as `