• Version 14.1.3
  • Published
  • 547 kB
  • 3 dependencies
  • MIT license


npm i @angular/localize
yarn add @angular/localize
pnpm add @angular/localize


Angular - library for localizing messages



variable ɵ_global

const ɵ_global: any;

    variable ɵ$localize

    const ɵ$localize: ɵLocalizeFn;
    • Tag a template literal string for localization.

      For example:

      $localize `some string to localize`

      **Providing meaning, description and id**

      You can optionally specify one or more of meaning, description and id for a localized string by pre-pending it with a colon delimited block of the form:

      $localize`:meaning|description@@id:source message text`;
      $localize`:meaning|:source message text`;
      $localize`:description:source message text`;
      $localize`:@@id:source message text`;

      This format is the same as that used for i18n markers in Angular templates. See the [Angular i18n guide](guide/i18n-common-prepare#mark-text-in-component-template).

      **Naming placeholders**

      If the template literal string contains expressions, then the expressions will be automatically associated with placeholder names for you.

      For example:

      $localize `Hi ${name}! There are ${items.length} items.`;

      will generate a message-source of Hi {$PH}! There are {$PH_1} items.

      The recommended practice is to name the placeholder associated with each expression though.

      Do this by providing the placeholder name wrapped in : characters directly after the expression. These placeholder names are stripped out of the rendered localized string.

      For example, to name the items.length expression placeholder itemCount you write:

      $localize `There are ${items.length}:itemCount: items`;

      **Escaping colon markers**

      If you need to use a : character directly at the start of a tagged string that has no metadata block, or directly after a substitution expression that has no name you must escape the : by preceding it with a backslash:

      For example:

      // message has a metadata block so no need to escape colon
      $localize `:some description::this message starts with a colon (:)`;
      // no metadata block so the colon must be escaped
      $localize `\:this message starts with a colon (:)`;

      // named substitution so no need to escape colon
      $localize `${label}:label:: ${}`
      // anonymous substitution so colon must be escaped
      $localize `${label}\: ${}`

      **Processing localized strings:**

      There are three scenarios:

      * **compile-time inlining**: the $localize tag is transformed at compile time by a transpiler, removing the tag and replacing the template literal string with a translated literal string from a collection of translations provided to the transpilation tool.

      * **run-time evaluation**: the $localize tag is a run-time function that replaces and reorders the parts (static strings and expressions) of the template literal string with strings from a collection of translations loaded at run-time.

      * **pass-through evaluation**: the $localize tag is a run-time function that simply evaluates the original template literal string without applying any translations to the parts. This version is used during development or where there is no need to translate the localized template literals.

      Parameter messageParts

      a collection of the static parts of the template string.

      Parameter expressions

      a collection of the values of each placeholder in the template string.


      the translated string, with the messageParts and expressions interleaved together.


    function clearTranslations

    clearTranslations: () => void;
    • Remove all translations for $localize, if doing runtime translation.

      All translations that had been loading into memory using loadTranslations() will be removed.

      See Also

      • loadTranslations() for loading translations at runtime.

      • $localize for tagging messages as needing to be translated.

    function loadTranslations

    loadTranslations: (translations: Record<MessageId, TargetMessage>) => void;
    • Load translations for use by $localize, if doing runtime translation.

      If the $localize tagged strings are not going to be replaced at compiled time, it is possible to load a set of translations that will be applied to the $localize tagged strings at runtime, in the browser.

      Loading a new translation will overwrite a previous translation if it has the same MessageId.

      Note that $localize messages are only processed once, when the tagged string is first encountered, and does not provide dynamic language changing without refreshing the browser. Loading new translations later in the application life-cycle will not change the translated text of messages that have already been translated.

      The message IDs and translations are in the same format as that rendered to "simple JSON" translation files when extracting messages. In particular, placeholders in messages are rendered using the {$PLACEHOLDER_NAME} syntax. For example the message from the following template:

      <div i18n>pre<span>inner-pre<b>bold</b>inner-post</span>post</div>

      would have the following form in the translations map:


      Parameter translations

      A map from message ID to translated message.

      These messages are processed and added to a lookup based on their MessageId.

      See Also

      • clearTranslations() for removing translations loaded using this function.

      • $localize for tagging messages as needing to be translated.

    function ɵfindEndOfBlock

    ɵfindEndOfBlock: (cooked: string, raw: string) => number;
    • Find the end of a "marked block" indicated by the first non-escaped colon.

      Parameter cooked

      The cooked string (where escaped chars have been processed)

      Parameter raw

      The raw string (where escape sequences are still in place)


      the index of the end of block marker


      an error if the block is unterminated

    function ɵisMissingTranslationError

    ɵisMissingTranslationError: (e: any) => e is ɵMissingTranslationError;

      function ɵmakeParsedTranslation

      ɵmakeParsedTranslation: (
      messageParts: string[],
      placeholderNames?: string[]
      ) => ɵParsedTranslation;
      • Create a ParsedTranslation from a set of messageParts and placeholderNames.

        Parameter messageParts

        The message parts to appear in the ParsedTranslation.

        Parameter placeholderNames

        The names of the placeholders to intersperse between the messageParts.

      function ɵmakeTemplateObject

      ɵmakeTemplateObject: (cooked: string[], raw: string[]) => TemplateStringsArray;
      • Create the specialized array that is passed to tagged-string tag functions.

        Parameter cooked

        The message parts with their escape codes processed.

        Parameter raw

        The message parts with their escaped codes as-is.

      function ɵparseMessage

      ɵparseMessage: (
      messageParts: TemplateStringsArray,
      expressions?: readonly any[],
      location?: ɵSourceLocation,
      messagePartLocations?: (ɵSourceLocation | undefined)[],
      expressionLocations?: (ɵSourceLocation | undefined)[]
      ) => ɵParsedMessage;
      • Parse a $localize tagged string into a structure that can be used for translation or extraction.

        See ParsedMessage for an example.

      function ɵparseMetadata

      ɵparseMetadata: (cooked: string, raw: string) => MessageMetadata;
      • Parse the given message part (cooked + raw) to extract the message metadata from the text.

        If the message part has a metadata block this function will extract the meaning, description, customId and legacyId (if provided) from the block. These metadata properties are serialized in the string delimited by |, @@ and respectively.

        (Note that is the LEGACY_ID_INDICATOR - see constants.ts.)

        For example:


        Parameter cooked

        The cooked version of the message part to parse.

        Parameter raw

        The raw version of the message part to parse.


        A object containing any metadata that was parsed from the message part.

      function ɵparseTranslation

      ɵparseTranslation: (messageString: TargetMessage) => ɵParsedTranslation;
      • Parse the messageParts and placeholderNames out of a target message.

        Used by loadTranslations() to convert target message strings into a structure that is more appropriate for doing translation.

        Parameter message

        the message to be parsed.

      function ɵsplitBlock

      ɵsplitBlock: (cooked: string, raw: string) => { text: string; block?: string };
      • Split a message part (cooked + raw) into an optional delimited "block" off the front and the rest of the text of the message part.

        Blocks appear at the start of message parts. They are delimited by a colon : character at the start and end of the block.

        If the block is in the first message part then it will be metadata about the whole message: meaning, description, id. Otherwise it will be metadata about the immediately preceding substitution: placeholder name.

        Since blocks are optional, it is possible that the content of a message block actually starts with a block marker. In this case the marker must be escaped \:.

        Parameter cooked

        The cooked version of the message part to parse.

        Parameter raw

        The raw version of the message part to parse.


        An object containing the text of the message part and the text of the block, if it exists.


        an error if the block is unterminated

      function ɵtranslate

      ɵtranslate: (
      translations: Record<string, ɵParsedTranslation>,
      messageParts: TemplateStringsArray,
      substitutions: readonly any[]
      ) => [TemplateStringsArray, readonly any[]];
      • Translate the text of the $localize tagged-string (i.e. messageParts and substitutions) using the given translations.

        The tagged-string is parsed to extract its messageId which is used to find an appropriate ParsedTranslation. If this doesn't match and there are legacy ids then try matching a translation using those.

        If one is found then it is used to translate the message into a new set of messageParts and substitutions. The translation may reorder (or remove) substitutions as appropriate.

        If there is no translation with a matching message id then an error is thrown. If a translation contains a placeholder that is not found in the message being translated then an error is thrown.


      class ɵMissingTranslationError

      class ɵMissingTranslationError extends Error {}


        constructor(parsedMessage: ɵParsedMessage);

          property parsedMessage

          readonly parsedMessage: ɵParsedMessage;


            interface ɵLocalizeFn

            interface ɵLocalizeFn {}

            property locale

            locale?: string;
            • The current locale of the translated messages.

              The compile-time translation inliner is able to replace the following code:

              typeof $localize !== "undefined" && $localize.locale

              with a string literal of the current locale. E.g.


            property translate

            translate?: ɵTranslateFn;
            • A function that converts an input "message with expressions" into a translated "message with expressions".

              The conversion may be done in place, modifying the array passed to the function, so don't assume that this has no side-effects.

              The expressions must be passed in since it might be they need to be reordered for different translations.

            call signature

            (messageParts: TemplateStringsArray, ...expressions: readonly any[]): string;

              interface ɵParsedMessage

              interface ɵParsedMessage extends MessageMetadata {}
              • Information parsed from a $localize tagged string that is used to translate it.

                For example:

                const name = 'Jo Bloggs';
                $localize`Hello ${name}:title@@ID:!`;

                May be parsed into:

                id: '6998194507597730591',
                substitutions: { title: 'Jo Bloggs' },
                messageString: 'Hello {$title}!',
                placeholderNames: ['title'],
                associatedMessageIds: { title: 'ID' },

              property associatedMessageIds

              associatedMessageIds?: Record<string, MessageId>;
              • An optional mapping of placeholder names to associated MessageIds. This can be used to match ICU placeholders to the message that contains the ICU.

              property id

              id: MessageId;
              • The key used to look up the appropriate translation target.

              property messagePartLocations

              messagePartLocations?: (ɵSourceLocation | undefined)[];
              • An optional mapping of message parts to source locations

              property messageParts

              messageParts: string[];
              • The static parts of the message.

              property placeholderNames

              placeholderNames: string[];
              • The names of the placeholders that will be replaced with substitutions.

              property substitutionLocations

              substitutionLocations?: Record<string, ɵSourceLocation | undefined>;
              • An optional mapping of placeholder names to source locations

              property substitutions

              substitutions: Record<string, any>;
              • A mapping of placeholder names to substitution values.

              interface ɵParsedTranslation

              interface ɵParsedTranslation extends MessageMetadata {}
              • A translation message that has been processed to extract the message parts and placeholders.

              property messageParts

              messageParts: TemplateStringsArray;

                property placeholderNames

                placeholderNames: string[];

                  interface ɵSourceLocation

                  interface ɵSourceLocation {}
                  • The location of the message in the source file.

                    The line and column values for the start and end properties are zero-based.

                  property end

                  end: {
                  line: number;
                  column: number;

                    property file

                    file: AbsoluteFsPathLocalizeCopy;

                      property start

                      start: {
                      line: number;
                      column: number;

                        property text

                        text?: string;

                          interface ɵTranslateFn

                          interface ɵTranslateFn {}

                          call signature

                          (messageParts: TemplateStringsArray, expressions: readonly any[]): [
                          readonly any[]

                            Type Aliases

                            type MessageId

                            type MessageId = string;
                            • A string that uniquely identifies a message, to be used for matching translations.

                            type ɵParsedTranslations

                            type ɵParsedTranslations = Record<MessageId, ɵParsedTranslation>;
                            • The internal structure used by the runtime localization to translate messages.

                            type ɵSourceMessage

                            type ɵSourceMessage = string;
                            • A string containing a translation source message.

                              I.E. the message that indicates what will be translated from.

                              Uses {$placeholder-name} to indicate a placeholder.

                            type TargetMessage

                            type TargetMessage = string;
                            • A string containing a translation target message.

                              I.E. the message that indicates what will be translated to.

                              Uses {$placeholder-name} to indicate a placeholder.

                            Package Files (1)

                            Dependencies (3)

                            Dev Dependencies (0)

                            No dev dependencies.

                            Peer Dependencies (2)


                            To add a badge like this onejsDocs.io badgeto your package's README, use the codes available below.

                            You may also use Shields.io to create a custom badge linking to https://www.jsdocs.io/package/@angular/localize.

                            • Markdown
                            • HTML
                              <a href="https://www.jsdocs.io/package/@angular/localize"><img src="https://img.shields.io/badge/jsDocs.io-reference-blue" alt="jsDocs.io"></a>