Skip to content

Angular RTL: right-to-left support in Angular apps

Configure Angular document direction, CDK bidi context, Material dialogs and Arabic pipe locale data, then test language changes and server rendering.

By , Founder of Ritla

Guide13 min read

An Angular page can have Arabic text flowing from the right while a Material overlay still uses an LTR direction context. A language switch can move the layout without changing a date pipe's locale. Those results are possible because HTML direction, CDK directionality and formatting locale are separate inputs.

The Angular CDK supplies a shared bidi context that components can inject. It does not translate application text or convert physical CSS properties into logical ones. Arabic locale data helps pipes format values, but it does not set document direction.

This guide follows a festival's badge-printing queue. The examples use standalone components, signals and the CDK's Directionality.value and change APIs. Use matching Angular, CDK and Material versions, and check imports against the installed major. The document token below follows the current Angular API, which exports DOCUMENT from @angular/core.

Separate the settings before changing a component#

Identify which setting the failing behavior actually consumes:

SettingWhat it suppliesWhat to inspect
HTML lang and dirDocument language and browser directionInitial HTML and rendered DOM
CDK Dir and DirectionalityDirection available through Angular injectionNearest provider, current value and change events
LOCALE_ID or an explicit pipe localeLocale used by formatting pipesProvider scope and pipe arguments
Application translationsHeadings, actions and feedbackMessages and accessible names
Component CSS and assetsSpacing, alignment and icon orientationWinning styles and rendered icons

A right-aligned heading does not establish that all these settings agree. Keep the same badge batch open while diagnosing, and compare its document attributes, injected direction and formatted summary separately.

For an Arabic document, begin with the root declaration:

html
<html lang="ar" dir="rtl">

The W3C direction guidance explains why language and direction need separate declarations. R001 covers document direction missing, contradicted, or declared only in CSS. That check does not establish which Angular injector supplies a popup's direction.

Inspect the initial response as well as the interactive DOM. A late browser update can make a screenshot look correct while the response still carries the wrong attributes. Keep that distinction visible throughout implementation and testing.

Bind a CDK direction boundary from the active locale#

Import BidiModule in the standalone component whose template contains the direction boundary. In an NgModule application, import it through the appropriate module instead.

This root component is a small layout-switching probe. It starts with Arabic, defines its own headings and applies document attributes through Angular's injected document:

ts
// src/app/app.component.tsimport { Component, DOCUMENT, computed, inject, signal } from '@angular/core';import { BidiModule } from '@angular/cdk/bidi'; type AppLocale = 'ar' | 'en';const localeSettings = {  ar: { lang: 'ar', dir: 'rtl', heading: 'طابور طباعة بطاقات المهرجان' },  en: { lang: 'en', dir: 'ltr', heading: 'Festival badge printing queue' },} as const; @Component({  selector: 'app-root',  standalone: true,  imports: [BidiModule],  template: `    <main [dir]="active().dir" #context="dir">      <h2>{{ active().heading }}</h2>      <button type="button" lang="ar" (click)="applyLocale('ar')">العربية</button>      <button type="button" lang="en" (click)="applyLocale('en')">English</button>      <output>{{ context.value }}</output>    </main>  `,})export class AppComponent {  private readonly document = inject(DOCUMENT);  readonly locale = signal<AppLocale>('ar');  readonly active = computed(() => localeSettings[this.locale()]);   constructor() {    this.applyLocale('ar');  }   applyLocale(locale: AppLocale): void {    this.locale.set(locale);    const settings = localeSettings[locale];    this.document.documentElement.lang = settings.lang;    this.document.documentElement.dir = settings.dir;  }}

Bootstrap it through the application's normal standalone entry. The output exposes the directive's current value for diagnosis; remove it from the production interface. The local heading dictionary makes the probe self-contained, not a replacement for the product's translation system.

The CDK's bidi guide explains that its Dir directive matches a dir boundary and provides a Directionality context to descendants. The template binding updates that directive's input while the application method updates document attributes. These have related responsibilities, but they are not the same operation.

Angular's binding guide distinguishes property and attribute binding. Use the CDK's [dir] input when configuring this context. A direct DOM attribute write is not evidence that Angular's direction context emitted an update.

The DOCUMENT token represents the rendering document in browser and server environments. In a real application, resolve the initial locale through the existing bootstrap or request integration before rendering. Replace the demonstration's fixed initial Arabic choice with that resolved value rather than independently detecting language in several components.

Read the nearest direction context and handle changes#

A component that depends on direction needs the initial value and later changes. Reading a value once and retaining it in an unrelated boolean creates a snapshot, not a live direction contract.

This diagnostic child seeds its signal during initialization and subscribes to later CDK changes:

ts
// src/app/direction-probe.component.tsimport { Component, OnInit, inject, signal } from '@angular/core';import { Directionality, type Direction } from '@angular/cdk/bidi';import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; @Component({  selector: 'app-direction-probe',  standalone: true,  template: `<output>{{ direction() }}</output>`,})export class DirectionProbeComponent implements OnInit {  private readonly bidi = inject(Directionality);  readonly direction = signal<Direction>('ltr');   constructor() {    this.bidi.change.pipe(takeUntilDestroyed()).subscribe(direction => {      this.direction.set(direction);    });  }   ngOnInit(): void {    this.direction.set(this.bidi.value);  }}

Add DirectionProbeComponent to the parent's imports and render app-direction-probe beneath its [dir] boundary. Verify the initial result, switch to English, then switch back without recreating the child. takeUntilDestroyed handles subscription cleanup through Angular's RxJS interoperability APIs.

Provider scope matters. A service injected at the application root does not acquire a descendant boundary just because its caller appears inside that boundary. Angular's hierarchical-injection guide explains the lookup model. Inspect where the direction-dependent component or service is created when its value disagrees with the DOM.

The root Directionality implementation reads initial document direction when constructed. Do not treat it as a general observer of every later html.dir mutation. The bound Dir context is the change-producing boundary for the subtree in this example.

Avoid mutating the injected service's value to force the result. Update the application's locale and its direction boundary, then let consumers observe that context. A nested English region should have a local boundary rather than changing the whole festival page.

Check for a stale dir on body too. The root service reads body.dir before html.dir, so an old body declaration can explain a surprising initial value. Correct the conflicting markup at its source. Adding another override around each failing component hides the disagreement and makes the next overlay harder to diagnose.

Initialization order deserves the same attention. A root-scoped consumer can obtain its direction before a component constructor updates document attributes. Moving the DOM write between lifecycle hooks does not create a subscription for that earlier consumer. Establish initial document direction before such consumers are created, and use an explicit bound context for changes within the running application.

Do not use CDK auto direction as content detection#

Native dir="auto" and CDK automatic direction are different mechanisms. The browser determines automatic direction from content under HTML's rules. The current CDK Dir implementation deliberately resolves its injected direction from the browser's language instead, while retaining the raw attribute on the element.

This can produce two answers at the same boundary: the browser lays out Arabic content as RTL, while a CDK consumer obtains LTR from an English browser preference. Changing the text is therefore not a reliable way to update the injected layout direction.

Use explicit rtl or ltr for the application shell and direction-aware component boundaries. Reserve content-based automatic direction for fields or text regions whose actual content requires it. Where BidiModule is in scope, inspect both the native element and the injected value rather than assuming that one confirms the other. The guide to automatic HTML direction covers the text-level decision separately.

Keep Material dialog direction explicit at the opening boundary#

Material overlays do not necessarily render inside the opener's DOM wrapper. A dialog can retain Angular injection relationships while living beneath a different DOM ancestor.

The overlay container implementation creates the shared overlay container outside ordinary component content. Inspect the open dialog's DOM direction instead of inferring it from where the trigger appears in a template.

For an explicit opening-time contract, read the caller's nearest direction and pass it to the dialog configuration:

ts
// badge-review.component.tsimport { Component, ViewContainerRef, inject } from '@angular/core';import { Directionality } from '@angular/cdk/bidi';import { MatDialog, MatDialogModule } from '@angular/material/dialog'; @Component({  selector: 'app-badge-review',  standalone: true,  imports: [MatDialogModule],  template: `<button type="button" (click)="openReview()">مراجعة دفعة البطاقات</button>`,})export class BadgeReviewComponent {  private readonly dialog = inject(MatDialog);  private readonly bidi = inject(Directionality);  private readonly viewContainerRef = inject(ViewContainerRef);   openReview(): void {    this.dialog.open(BadgeBatchDialogComponent, {      direction: this.bidi.value,      viewContainerRef: this.viewContainerRef,      ariaLabelledBy: 'badge-batch-review-title',    });  }} @Component({  standalone: true,  imports: [MatDialogModule],  template: `    <h2 mat-dialog-title id="badge-batch-review-title">مراجعة بيانات الدفعة</h2>    <mat-dialog-content>راجع أسماء الجهات قبل اعتماد الطباعة.</mat-dialog-content>    <mat-dialog-actions>      <button type="button" mat-dialog-close>العودة إلى قائمة البطاقات</button>    </mat-dialog-actions>  `,})export class BadgeBatchDialogComponent {}

Render BadgeReviewComponent below the CDK boundary, with the application's Material theme and required framework setup already in place. The Arabic strings form a review fixture; translate them through the product's message system when integrating it.

The dialog configuration source distinguishes direction from viewContainerRef: the latter affects the logical component tree and injection, not the physical render location. The dialog guide documents the dialog service and content directives.

This configuration selects a direction when opening. Do not assume the same string will update an already-open dialog when the application changes language. Decide whether the product closes overlays during a switch or updates them through the component's supported contract. Test the chosen behavior, including title translation, focus entry, dismissal and focus return.

Closing a review dialog during a language switch also needs a state policy. Preserve any unfinished review in application state before rebuilding the interface, and restore focus to a trigger that still exists. If switching instead navigates to a separately localized application, test that navigation with an unfinished batch. Direction consistency is only one acceptance condition; losing the operator's selection would make the switch unusable even if the next dialog opens correctly.

For custom CDK overlays, OverlayRef exposes direction and position operations in its public implementation. Keep text direction and positioning under review separately; setting a direction attribute does not prove the overlay remains inside the viewport. Avoid reaching through Material's private fields to obtain its internal overlay reference.

Register Arabic locale data separately from direction#

Angular's built-in formatting pipes use LOCALE_ID unless an explicit locale argument is provided. Registering Arabic data makes that locale available; selecting RTL layout does not register it.

For a manually configured Arabic bootstrap using the earlier root component:

ts
// src/main.tsimport { LOCALE_ID } from '@angular/core';import { registerLocaleData } from '@angular/common';import ar from '@angular/common/locales/ar';import { bootstrapApplication } from '@angular/platform-browser';import { AppComponent } from './app/app.component'; registerLocaleData(ar);bootstrapApplication(AppComponent, {  providers: [{ provide: LOCALE_ID, useValue: 'ar' }],}).catch(error => console.error(error));

Merge the provider into the application's existing configuration rather than discarding its router, HTTP or other providers. This snippet establishes an Arabic formatting default; it does not make LOCALE_ID follow the root probe's English button.

Angular documents registerLocaleData and locale-based formatting. When the CLI builds localized application variants, its localization flow can register the required locale data for those builds. Check that integration before adding a second registration mechanism.

Do not use LOCALE_ID as a mutable language-switch signal. Existing pipes and services have already obtained dependencies from their injector. For runtime formatting changes, pass the active formatting locale as a pipe argument or use a formatter designed around that changing input.

Keep the locale identifier deliberate. Arabic language support does not mean every market shares date, calendar or number requirements. Angular's locale-ID guidance explains the role of regional identifiers.

Pass changing locales to pipes explicitly#

This summary component receives its formatting locale from the parent instead of taking an initial snapshot of the application's language:

ts
// batch-summary.component.tsimport { Component, Input } from '@angular/core';import { DatePipe, DecimalPipe } from '@angular/common'; @Component({  selector: 'app-batch-summary',  standalone: true,  imports: [DatePipe, DecimalPipe],  template: `    <p>{{ badgeCount | number:'1.0-0':formatLocale }}</p>    <p>{{ collectionAt | date:'longDate':'+0000':formatLocale }}</p>  `,})export class BatchSummaryComponent {  @Input() formatLocale = 'ar';  readonly badgeCount = 1836;  readonly collectionAt = new Date('2033-09-21T13:25:00Z');}

Import this component into its parent and bind formatLocale from the same active locale choice, using ar for Arabic and en-US for the English formatting choice in this probe. The Arabic data must be available through registration or the localized build.

The DecimalPipe API documents its locale argument. The DatePipe API documents the format, time-zone and locale arguments. The explicit UTC offset here makes the diagnostic date independent of the machine's default time zone; replace that policy with the event's actual display requirements.

Inspect the number and date actually rendered. Do not assume Angular pipe output and an unrelated Intl formatter choose identical digits or punctuation. Set the product's number policy, then verify each formatting path against it. For deeper date-display decisions, use dates and times inside RTL interfaces.

Treat date values as immutable inputs when updating this summary. Mutating an existing Date object is not the same as supplying a changed reference to a pure pipe. Also test a language change while the underlying count and timestamp remain unchanged; that specifically exercises the changing locale argument.

Translate Material labels through their own APIs#

An RTL paginator can still announce English navigation labels. Directionality controls layout behavior, not every string in a Material component.

For pagination, MatPaginatorIntl supplies labels and the range-message function. A provider can supply the application's reviewed Arabic wording. If those labels change after initialization, its changes stream exists to notify consumers. Updating fields without the corresponding notification is not a complete runtime update.

Review the range message as well as the page-size caption and next/previous names. Test empty results and a partial final page. Keep count formatting consistent with the badge summary instead of inserting raw numbers into otherwise translated text by accident.

Date pickers have another boundary. The date-adapter API defines MAT_DATE_LOCALE, adapter locale changes and adapter-specific date behavior. A translated calendar label and an Arabic-formatted date are separate outcomes. Check the adapter and internationalized control labels used by the installed Material version.

For application-owned text, Angular's translation-preparation guide covers template messages, attribute text and code messages. Include validation, helper text and accessible names. A heading changing language does not establish that a failed print request's error message changes too.

Component encapsulation does not repair physical CSS#

Angular's style encapsulation changes selector scope, not the meaning of physical padding. Suppose the badge summary reserves more room at reading end than at reading start. Its existing horizontal LTR padding is:

css
/* Problem: the badge summary component's own stylesheet. */:host {  display: block;  padding: 18px 34px 18px 22px;}

The four-value shorthand fixes the larger inset to the physical right. Preserve the English measurements while expressing the intended relationship:

css
:host {  display: block;  padding-block: 18px;  padding-inline: 22px 34px;}

In horizontal LTR, the left padding remains the start value and the right padding remains the end value. Horizontal RTL exchanges their physical mapping. The logical-properties specification defines those relationships; Angular's styling guide explains the separate encapsulation mechanism.

R030 covers direction-sensitive physical properties without an RTL override. Inspect inline style bindings and third-party CSS too. Keep intentional physical measurements, such as a marker on the printed badge artwork, attached to the same artwork feature rather than mirroring them as interface spacing.

Do not reverse every flex row or reorder the badge array to obtain Arabic layout. Preserve record identity and reading sequence, then test DOM order, keyboard navigation and wrapping. Review custom arrows against the action they advance using what should be mirrored in RTL.

Keep technical values and Arabic text in their own boundaries#

Angular interpolation renders a value into text; it does not automatically isolate that value's bidi behavior. Review badge references and foreign organization names where they appear inside Arabic messages. Keep a technical identifier intact without forcing the whole message LTR. See Arabic and English mixed text for the corresponding markup decisions.

For editable technical values, set direction on the native control that owns the value. An Arabic label around an email or URL field does not require the value itself to be RTL. Conversely, ordinary Arabic participant notes should retain Arabic input direction.

R070 covers telephone, email and URL inputs rendered RTL. When a custom Angular form component wraps the native input, inspect where its dir input or attribute actually lands. An attribute on the component host can be inherited by several children, while an unimplemented component input may not reach the native field at all. Use Arabic text input direction when the field's content contract needs further work.

Render the initial locale consistently on the server#

The root probe's fixed Arabic choice is for demonstration. In a server-rendered product, resolve the request's supported locale and use the same choice for translations, root attributes, CDK boundaries and formatting inputs.

Angular's SSR guide documents the rendering document and request context. Do not read browser-only storage during server rendering or keep a request's locale in mutable process-wide state. Follow the application's bootstrap integration so the browser starts with the same locale as the response.

Angular's built-in localization workflow can produce separate translated application variants. Its translation-merging guide describes localized builds and their language attributes. That workflow is different from swapping a runtime dictionary in one existing application instance. Choose the product's switching model before promising that a locale token or document mutation translates every component.

Inspect generated and server-rendered Arabic HTML before hydration. Confirm that the document already declares the intended language and direction. A client lifecycle hook can change the later page without establishing that the response was correct.

Compare direct loads, deep-link refreshes and navigation between languages. Angular's hydration guide explains the need for compatible server and client DOM. Diagnose differences in the locale handoff rather than suppressing warnings while leaving the initial layout inconsistent.

For localized deployments, request the Arabic deep link directly rather than reaching it only through the language selector. Verify that the response contains the intended translated shell and that its assets load from the deployment's actual base path. A successful client-side transition can bypass a misconfigured server fallback. Include a fresh browser session so a stored language preference cannot conceal the response's initial choice.

Test the injected context and the rendered interface#

Keep the same badge batch selected and verify initial Arabic rendering, English rendering and a return switch. Include an open dialog, unsent notes and the unchanged count and date used by the formatting probe.

  • Inspect root attributes in the response and after application startup.
  • Verify the nearest CDK direction value and its updates without recreating the child.
  • Open Material overlays and inspect their rendered direction, focus behavior and viewport fit.
  • Compare pipe output before and after changing only its explicit locale argument.
  • Test translated labels, validation and pending or failed request states.
  • Compare component spacing, tab order and wrapping at narrow widths.
  • Repeat the journey against the production build and its deployment paths.

Use a host component with a bound Dir boundary when testing a direction-aware child. A constant injected test double can verify an initial value, but it cannot establish that the template directive emits the required updates. Angular's component-testing scenarios explain binding and stabilization; wait for the relevant rendering state before asserting the DOM.

When a failure appears, follow the setting to its first disagreement:

Observed resultNext diagnostic step
Document RTL, diagnostic child LTRCheck the nearest provider and whether the child is beneath the intended bound Dir
Child updates, newly opened dialog disagreesInspect the opener's injected value and the configuration passed to that opening
New dialogs agree, an existing dialog does notExercise the product's policy for overlays already open during switching
Direction changes, date stays in EnglishInspect the pipe's explicit locale or injected formatting default
Context agrees, one inset stays physicalInspect the component's winning CSS declaration and any inline binding

Use those observations to narrow the repair. Replacing the direction service cannot fix a pipe argument, and translating a button cannot fix a physical inset. Repeat the original interaction after the targeted change, including the return switch, so the English state is checked too.

Keep browser layout checks alongside component assertions. An injected rtl value cannot show whether a long Arabic label is clipped, and a screenshot cannot establish that a paginator's accessible name is translated. Record the component state and the evidence appropriate to each failure.

A free Ritla scan of the Arabic badge queue can surface missing or contradictory document direction and direction-sensitive physical properties without RTL overrides. Continue with Arabic text input direction for native-control boundaries, or debugging RTL layout problems when HTML and CDK context agree but a component still lays out incorrectly.

Checks in this guide

See what your Arabic pages are hiding

Paste a URL. Ritla renders the page on desktop and mobile, runs every check, and shows the top issues with screenshot evidence.

Scan a page freeBrowse the checks