For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt, and this page is available as Markdown at /api/angular-lynx/hardware/nfc.md.

LynxNfc

Reads and writes NFC tags: a membership card, a museum label, a smart-home tag or a device you're setting up. import { LynxNfc } from '@blotch/angular-lynx';

An NFC tag holds an NDEF message: a short list of records, such as a link or some text. LynxNfc reads those records and writes new ones.

Turn it on

Add permissions.nfc to the build target's options in angular.json, with the reason your app reads tags:

angular.json
"options": {
  "permissions": { "nfc": "Reads your membership card" }
}

What it adds:

  • iOS: NFCReaderUsageDescription, and the NFC Tag Reading entitlement.
  • Android: the NFC permission, granted at install. The NFC feature is declared not required, so Google Play still offers the app to phones without NFC.

Without it, the native code is left out of both apps. state is then unsupported, and every call rejects with unsupported.

A paid Apple team

A free Personal Team can't sign the NFC Tag Reading entitlement. Set ios.teamId to a team in the paid Apple Developer Program to run the app on an iPhone. The Simulator needs no team, but it has no NFC reader.

See Turn on device features for every setting.

Usage

import { Component, inject, signal } from '@angular/core';
import { LYNX_ELEMENTS, LynxNfc, NfcError } from '@blotch/angular-lynx';

@Component({
  selector: 'app-member-card',
  imports: [LYNX_ELEMENTS],
  template: `
    @if (nfc.state() === 'ready') {
      <view (bindtap)="readCard()"><text>Scan your card</text></view>
    } @else if (nfc.state() === 'disabled') {
      <text>Turn on NFC in Settings to scan your card</text>
    }
    <text>{{ status() }}</text>
  `,
})
export class MemberCard {
  readonly nfc = inject(LynxNfc);
  readonly status = signal('');

  async readCard() {
    try {
      const tag = await this.nfc.read({
        alertMessage: 'Hold your card near the top of the phone',
      });
      const link = tag.records.find((record) => record.type === 'url');
      this.status.set(link ? `Member: ${link.value}` : 'This card is empty');
    } catch (error) {
      if (error instanceof NfcError && error.code === 'canceled') return;
      this.status.set((error as Error).message);
    }
  }
}

On iOS, read() opens the system's scan sheet with your alertMessage. On Android there's no sheet: show your own "Hold your phone near the tag" while the call is open.

Write a tag

await this.nfc.write(
  [
    { type: 'url', value: 'https://example.com/members/42' },
    { type: 'text', value: 'Member 42' },
  ],
  { alertMessage: 'Hold the tag near the phone', successMessage: 'Saved' },
);

write() replaces what the next tag holds.

  • A locked tag rejects with readOnly.
  • Records that don't fit reject with tooLarge. Only the tag can tell.
  • No records, or an invalid one, throw a TypeError before any tag comes near. A mime record without a media type is invalid, for example.

Read several tags

readonly #scan = signal<NfcScan | undefined>(undefined);

async startScanning() {
  this.#scan.set(
    await this.nfc.scan({ alertMessage: 'Tap each item' }, (tag) => {
      this.items.update((items) => [...items, tag]);
    }),
  );
}

async stopScanning() {
  await this.#scan()?.stop();
}

scan() calls back with each tag until you call stop(), or until the scan ends by itself:

  • the person closes iOS's sheet (canceled)
  • it times out (timeout)
  • the system fails (failed)

Its error signal then holds the reason, and scanning turns false.

A tag it can't read is skipped, and a tag held near the phone may be read again. On iOS the sheet stays up for the whole scan.

Methods

MethodReturnsDescription
read(options?)Promise<NfcTag>Waits for one tag and resolves with it
write(records, options?)Promise<NfcTag>Writes records to the next tag, and resolves with the tag as written
scan(options, onTag)Promise<NfcScan>Calls onTag with each tag until stop(). Resolves once the phone listens
stateSignal<NfcState>ready, disabled (NFC off in Android's settings), unsupported or unknown (not asked yet)

Only one call is open at a time: another rejects with busy. state is asked again each time the app comes back to the foreground, so it turns ready after the person turns NFC on in Settings.

NfcSessionOptions

OptionTypeDescription
alertMessagestringWhat iOS's scan sheet says. iOS only
successMessagestringWhat iOS's sheet says as it closes after a tag worked. iOS only

NfcTag

FieldTypeDescription
recordsreadonly NfcRecord[]The records it holds, in order. None on an empty tag
writablebooleanWhether write() can write to it
capacitynumberThe most bytes its message takes, or 0 when the tag doesn't say
idstring | undefinedIts serial number, as hex. Android only. Don't use it to grant access

NfcRecord

typeFieldsWhat it is
textvalue, lang (such as en)Text. write() takes lang as optional, en by default
urlvalueA link, a tel: number or a mailto: address
mimemediaType, data: Uint8ArrayData of a media type, such as application/json
othertnf, recordType: Uint8Array, dataAny other record, raw, for an app that knows its format

NfcError

Every call rejects with an NfcError (apart from write()'s TypeError for invalid records), whose code is one of:

CodeWhen
unsupportedNo NFC reader, or the app was built without permissions.nfc
disabledNFC is turned off in Android's settings
canceledThe person closed iOS's sheet
timeoutiOS closed its sheet after a minute with no tag
busyAnother call is still open
tagNotNdefThe tag holds no NDEF records, such as a payment or transit card
readOnlywrite()'s tag is locked
tooLargeThe records don't fit on the tag
failedThe tag moved away too soon, or the system failed

Platform support

PlatformSupport
iOSiPhone 7 and later, with Core NFC's scan sheet. Not on iPad or Simulator
AndroidPhones with NFC, while the app is in the foreground
Web previewunsupported
Lynx Explorerunsupported

Testing

The testing library fakes the reader. tapNfcTag() brings a tag near the phone:

fireEvent.tap(screen.getByText('Scan your card'));
tapNfcTag({ records: [{ type: 'url', value: 'https://example.com/m/42' }] });
await waitForUpdate();
expect(
  screen.getByText('Member: https://example.com/m/42'),
).toBeInTheDocument();