Components and Theming
|
This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production. |
Ionic ships more than a hundred UI components as web components, all prefixed ion-. They provide the structure of
a mobile screen — header, content area, lists, forms, overlays, tabs — and adapt their look and behaviour to the
platform. This page introduces the components a typical app needs, shows how they are imported in an Angular
standalone project, explains theming and dark mode, and then builds the two main Trailhead screens: the trail
list with search and the trail detail page. The project setup is on
Getting Started with Ionic and Capacitor; moving between the pages is
on Navigation and Routing. The Angular fundamentals used here
are in the Angular reference, in particular
components and signals.
Standalone Imports and Application Setup
In an Angular standalone project each Ionic component is a standalone class imported from
@ionic/angular/standalone and listed in the imports array of the component that uses it. Only the components
actually imported end up in the bundle, which keeps the application small. Importing from the package root
@ionic/angular instead pulls in everything and is the older, module-based style.
The application is configured once in main.ts. provideIonicAngular registers Ionic, and IonicRouteStrategy
lets the router keep pages alive for stack navigation:
// src/main.ts
import { bootstrapApplication } from '@angular/platform-browser';
import { RouteReuseStrategy, provideRouter, withComponentInputBinding } from '@angular/router';
import { provideHttpClient } from '@angular/common/http';
import { IonicRouteStrategy, provideIonicAngular } from '@ionic/angular/standalone';
import { AppComponent } from './app/app.component';
import { routes } from './app/app.routes';
bootstrapApplication(AppComponent, {
providers: [
{ provide: RouteReuseStrategy, useClass: IonicRouteStrategy },
provideIonicAngular(),
provideRouter(routes, withComponentInputBinding()),
provideHttpClient(),
],
});
The Component Toolbox
| Component | Purpose |
|---|---|
|
The root element. It sets up the layout, safe areas and overlay containers. Every app has one. |
|
The top bar. |
|
The scrollable page body. It owns scrolling, pull-to-refresh and infinite scroll, so do not scroll the page itself. |
|
Lists of rows. An item can hold avatars, thumbnails, icons, toggles and sliding actions. |
|
Buttons with fill, size and colour options, and a floating action button. |
|
A search field with a clear button and debounced change events. |
|
A dialog sheet over the page. It can be a full-screen page, a card on iOS or a bottom sheet with breakpoints. |
|
Pull-to-refresh as a child of |
|
Bottom tab navigation. The tabs integrate with the router. |
|
Form controls with labels, helper text and error text built in. |
Short-lived overlays are created from code through controllers, which are injectable Angular services:
ToastController, AlertController, ActionSheetController, LoadingController and ModalController. A
controller creates the overlay, then present() shows it:
import { Injectable, inject } from '@angular/core';
import { ToastController } from '@ionic/angular/standalone';
@Injectable({ providedIn: 'root' })
export class FeedbackService {
private readonly toasts = inject(ToastController);
async saved(message: string): Promise<void> {
const toast = await this.toasts.create({ message, duration: 2000, position: 'bottom' });
await toast.present();
}
}
An alert or a toast should not carry long forms: use an ion-modal for anything with real input.
Adaptive Styling: iOS and Material Design
Every Ionic component renders in one of two modes: ios or md (Material Design). The default is chosen from
the platform, so the same markup looks native on each device: iOS gets centred titles, large collapsible headers
and translucent bars, while Android gets left-aligned titles and ripple effects. Page transitions follow the same
rule — a horizontal slide on iOS and a fade-and-lift on Android.
The mode can be forced for the whole app with provideIonicAngular({ mode: 'md' }), which is useful for screenshots
or a consistent brand look. Style rules that depend on the mode use the .ios and .md classes Ionic puts on the html element.
Theming with CSS Variables
Ionic components are styled with CSS custom properties, so a theme is a stylesheet and not a rebuild. The starter
project keeps them in src/theme/variables.scss. Colours come as a colour family: a base, a contrast colour for
text on top of it, and shade and tint variants:
:root {
--ion-color-primary: #2e7d32;
--ion-color-primary-rgb: 46, 125, 50;
--ion-color-primary-contrast: #ffffff;
--ion-color-primary-contrast-rgb: 255, 255, 255;
--ion-color-primary-shade: #286e2c;
--ion-color-primary-tint: #438a47;
--ion-font-family: 'Inter', system-ui, sans-serif;
}
Ionic ships a palette of named colours — primary, secondary, tertiary, success, warning, danger,
light, medium and dark — selected with the color attribute: <ion-button color="danger">. Component-level
variables such as --background, --color and --padding-start customize one component, either globally or
through a CSS class. The Ionic color generator in the documentation produces all the variants for a brand colour.
Rules that must reach into a component’s shadow DOM use the documented CSS shadow parts, for example
ion-searchbar::part(...) where a component exposes one.
Dark Mode
Ionic provides ready-made dark palettes that follow the operating system setting through the CSS
prefers-color-scheme media query. The system palette is enabled by importing a stylesheet in global.scss:
@import "@ionic/angular/css/palettes/dark.system.css";
Other variants are dark.always.css (always dark) and dark.class.css, which switches on a .ion-palette-dark
class that the app toggles itself, the right choice for a manual theme option. Custom colours should be redefined
for the dark palette so brand colours keep enough contrast.
Safe Areas and Edge-to-Edge
Ionic’s header, footer and content respect the device safe areas (notch, home indicator, system bars)
automatically. Custom elements outside those components use the CSS env() function, for example
padding-bottom: env(safe-area-inset-bottom), and the viewport meta tag needs viewport-fit=cover for the values to
be non-zero on iOS. In Capacitor 8 the former android.adjustMarginsForEdgeToEdge option no longer exists: the web
layer handles edge-to-edge with these CSS variables, and the System Bars core plugin controls status and navigation
bar appearance.
The Trailhead Data Model and Service
Both screens read trails from the REST API at https://api.example.com/v1. A signal-based service keeps the list
state and the search term:
// src/app/trails/trail.service.ts
import { HttpClient } from '@angular/common/http';
import { Injectable, computed, inject, signal } from '@angular/core';
import { firstValueFrom } from 'rxjs';
export type Difficulty = 'easy' | 'moderate' | 'hard';
export interface Trail {
id: string;
name: string;
lengthKm: number;
difficulty: Difficulty;
}
const API = 'https://api.example.com/v1';
@Injectable({ providedIn: 'root' })
export class TrailService {
private readonly http = inject(HttpClient);
readonly trails = signal<Trail[]>([]);
readonly query = signal('');
readonly filtered = computed(() => {
const term = this.query().trim().toLowerCase();
return this.trails().filter((trail) => trail.name.toLowerCase().includes(term));
});
async load(): Promise<void> {
this.trails.set(await firstValueFrom(this.http.get<Trail[]>(`${API}/trails`)));
}
async get(id: string): Promise<Trail> {
return firstValueFrom(this.http.get<Trail>(`${API}/trails/${id}`));
}
}
Offline caching of this list is added on Data, Storage and Networking.
The Trail List Page
The list page combines ion-searchbar, ion-refresher and ion-list. Each row links to the detail route:
// src/app/trails/trail-list.page.ts
import { Component, inject } from '@angular/core';
import { RouterLink } from '@angular/router';
import {
IonBadge, IonContent, IonHeader, IonItem, IonLabel, IonList, IonRefresher, IonRefresherContent,
IonSearchbar, IonTitle, IonToolbar, RefresherCustomEvent, SearchbarCustomEvent,
} from '@ionic/angular/standalone';
import { TrailService } from './trail.service';
@Component({
selector: 'app-trail-list',
templateUrl: 'trail-list.page.html',
imports: [
RouterLink, IonHeader, IonToolbar, IonTitle, IonContent, IonSearchbar,
IonRefresher, IonRefresherContent, IonList, IonItem, IonLabel, IonBadge,
],
})
export class TrailListPage {
protected readonly service = inject(TrailService);
protected onSearch(event: SearchbarCustomEvent): void {
this.service.query.set(event.detail.value ?? '');
}
protected async onRefresh(event: RefresherCustomEvent): Promise<void> {
await this.service.load();
await event.target.complete();
}
}
<!-- src/app/trails/trail-list.page.html -->
<ion-header>
<ion-toolbar>
<ion-title>Trails</ion-title>
</ion-toolbar>
<ion-toolbar>
<ion-searchbar placeholder="Search trails" [debounce]="250" (ionInput)="onSearch($event)"></ion-searchbar>
</ion-toolbar>
</ion-header>
<ion-content>
<ion-refresher slot="fixed" (ionRefresh)="onRefresh($event)">
<ion-refresher-content></ion-refresher-content>
</ion-refresher>
<ion-list>
@for (trail of service.filtered(); track trail.id) {
<ion-item [routerLink]="['/trails', trail.id]" detail="true">
<ion-label>
<h2>{{ trail.name }}</h2>
<p>{{ trail.lengthKm }} km</p>
</ion-label>
<ion-badge slot="end" [color]="trail.difficulty === 'hard' ? 'danger' : 'success'">
{{ trail.difficulty }}
</ion-badge>
</ion-item>
} @empty {
<ion-item lines="none"><ion-label>No trails found.</ion-label></ion-item>
}
</ion-list>
</ion-content>
The list is loaded when the page is entered, and the page lifecycle for that is covered on
Navigation and Routing. For long lists, add an ion-infinite-scroll after the ion-list and handle (ionInfinite).
The Trail Detail Page
The detail page reads the route parameter, shows the trail, and offers a favourite toggle and a link to log a hike.
The route parameter is bound to an input because the router is configured with withComponentInputBinding():
// src/app/trails/trail-detail.page.ts
import { Component, effect, inject, input, signal } from '@angular/core';
import { RouterLink } from '@angular/router';
import {
IonBackButton, IonButton, IonButtons, IonContent, IonHeader, IonIcon, IonTitle, IonToolbar,
} from '@ionic/angular/standalone';
import { addIcons } from 'ionicons';
import { heart, heartOutline } from 'ionicons/icons';
import { Trail, TrailService } from './trail.service';
@Component({
selector: 'app-trail-detail',
templateUrl: 'trail-detail.page.html',
imports: [RouterLink, IonHeader, IonToolbar, IonButtons, IonBackButton, IonTitle, IonContent, IonButton, IonIcon],
})
export class TrailDetailPage {
readonly id = input.required<string>();
protected readonly trail = signal<Trail | undefined>(undefined);
protected readonly favourite = signal(false);
private readonly service = inject(TrailService);
constructor() {
addIcons({ heart, heartOutline });
effect(() => {
void this.service.get(this.id()).then((value) => this.trail.set(value));
});
}
protected toggleFavourite(): void {
this.favourite.update((value) => !value);
}
}
<!-- src/app/trails/trail-detail.page.html -->
<ion-header>
<ion-toolbar>
<ion-buttons slot="start"><ion-back-button defaultHref="/trails"></ion-back-button></ion-buttons>
<ion-title>{{ trail()?.name }}</ion-title>
<ion-buttons slot="end">
<ion-button (click)="toggleFavourite()" aria-label="Toggle favourite">
<ion-icon slot="icon-only" [name]="favourite() ? 'heart' : 'heart-outline'"></ion-icon>
</ion-button>
</ion-buttons>
</ion-toolbar>
</ion-header>
<ion-content class="ion-padding">
@if (trail(); as t) {
<h1>{{ t.name }}</h1>
<p>{{ t.lengthKm }} km, {{ t.difficulty }}</p>
<ion-button expand="block" [routerLink]="['/trails', t.id, 'log']">Log a hike</ion-button>
}
</ion-content>
The favourite state here is local to the page; persisting it is a data concern covered later. The camera and GPS part of the "Log a hike" page is on Capacitor Plugins.