Overview
The @angular/platform-browser package provides the infrastructure for running Angular applications in a web browser. It includes bootstrapping APIs, DOM manipulation services, and security utilities for browser-based applications.
Bootstrap Functions
bootstrapApplication
Bootstraps a standalone component as the root of an Angular application.
function bootstrapApplication (
rootComponent : Type < unknown >,
options ?: ApplicationConfig ,
context ?: BootstrapContext
) : Promise < ApplicationRef >
A standalone component to render as the application root.
Configuration object containing providers and other application settings.
Optional context providing a pre-existing platform injector (useful for server-side rendering).
Returns: Promise<ApplicationRef> - The bootstrapped application reference.
Example:
import { bootstrapApplication } from '@angular/platform-browser' ;
import { Component } from '@angular/core' ;
import { provideRouter } from '@angular/router' ;
import { provideHttpClient } from '@angular/common/http' ;
@ Component ({
selector: 'app-root' ,
standalone: true ,
template: '<h1>Hello World!</h1>'
})
class AppComponent {}
bootstrapApplication ( AppComponent , {
providers: [
provideRouter ( routes ),
provideHttpClient ()
]
});
The root component must be a standalone component. Use standalone: true in the component decorator.
createApplication
Creates an Angular application without bootstrapping any components. Components can be bootstrapped later using the returned ApplicationRef.
function createApplication (
options ?: ApplicationConfig ,
context ?: BootstrapContext
) : Promise < ApplicationRef >
Configuration object containing providers and other application settings.
Optional context providing a pre-existing platform injector.
Returns: Promise<ApplicationRef> - Application reference for manual component bootstrapping.
Example:
import { createApplication } from '@angular/platform-browser' ;
import { provideRouter } from '@angular/router' ;
const appRef = await createApplication ({
providers: [ provideRouter ( routes )]
});
// Bootstrap components manually later
await appRef . bootstrap ( MyComponent );
Creates a browser platform instance. This is typically used for advanced scenarios where you need explicit control over platform creation.
function platformBrowser (
extraProviders ?: StaticProvider []
) : PlatformRef
Optional additional platform-level providers.
Returns: PlatformRef - Browser platform reference.
Example:
import { platformBrowser } from '@angular/platform-browser' ;
import { AppModule } from './app.module' ;
const platform = platformBrowser ();
platform . bootstrapModule ( AppModule );
Modules
BrowserModule
Exports required infrastructure for all Angular apps running in a browser. Includes CommonModule and ApplicationModule.
@ NgModule ({
exports: [ CommonModule , ApplicationModule ]
})
class BrowserModule {}
Example:
import { NgModule } from '@angular/core' ;
import { BrowserModule } from '@angular/platform-browser' ;
import { AppComponent } from './app.component' ;
@ NgModule ({
declarations: [ AppComponent ],
imports: [ BrowserModule ],
bootstrap: [ AppComponent ]
})
export class AppModule {}
BrowserModule should only be imported once in your root module. Child modules should import CommonModule instead.
Services
Title
Service for getting and setting the HTML document title.
@ Injectable ({ providedIn: 'root' })
class Title {
getTitle () : string
setTitle ( newTitle : string ) : void
}
Methods:
Returns the current document title.
setTitle
(newTitle: string) => void
Sets the document title.
Example:
import { Component , inject } from '@angular/core' ;
import { Title } from '@angular/platform-browser' ;
@ Component ({
selector: 'app-user-profile' ,
template: '<h1>User Profile</h1>'
})
export class UserProfileComponent {
private title = inject ( Title );
ngOnInit () {
this . title . setTitle ( 'User Profile - My App' );
}
}
Service for managing HTML <meta> tags. Essential for SEO, social sharing, and security configurations.
@ Injectable ({ providedIn: 'root' })
class Meta {
addTag ( tag : MetaDefinition , forceCreation ?: boolean ) : HTMLMetaElement | null
addTags ( tags : MetaDefinition [], forceCreation ?: boolean ) : HTMLMetaElement []
getTag ( attrSelector : string ) : HTMLMetaElement | null
getTags ( attrSelector : string ) : HTMLMetaElement []
updateTag ( tag : MetaDefinition , selector ?: string ) : HTMLMetaElement | null
removeTag ( attrSelector : string ) : void
removeTagElement ( meta : HTMLMetaElement ) : void
}
MetaDefinition Type:
type MetaDefinition = {
charset ?: string
content ?: string
httpEquiv ?: string
id ?: string
itemprop ?: string
name ?: string
property ?: string
scheme ?: string
url ?: string
[ prop : string ] : string
}
Methods:
addTag
(tag: MetaDefinition, forceCreation?: boolean) => HTMLMetaElement | null
Adds a meta tag to the document. If forceCreation is false (default), returns existing tag if found.
addTags
(tags: MetaDefinition[], forceCreation?: boolean) => HTMLMetaElement[]
Adds multiple meta tags to the document.
getTag
(attrSelector: string) => HTMLMetaElement | null
Retrieves a meta tag using an attribute selector (e.g., "name='description'").
getTags
(attrSelector: string) => HTMLMetaElement[]
Retrieves all meta tags matching the attribute selector.
updateTag
(tag: MetaDefinition, selector?: string) => HTMLMetaElement | null
Updates an existing meta tag or creates one if it doesn’t exist.
removeTag
(attrSelector: string) => void
Removes a meta tag matching the attribute selector.
Example:
import { Component , inject } from '@angular/core' ;
import { Meta } from '@angular/platform-browser' ;
@ Component ({
selector: 'app-article' ,
template: '<article>...</article>'
})
export class ArticleComponent {
private meta = inject ( Meta );
ngOnInit () {
// Add meta tags for SEO and social sharing
this . meta . addTags ([
{ name: 'description' , content: 'Article description for SEO' },
{ name: 'keywords' , content: 'angular, typescript, web' },
{ property: 'og:title' , content: 'Article Title' },
{ property: 'og:description' , content: 'Social sharing description' },
{ property: 'og:image' , content: 'https://example.com/image.jpg' },
{ name: 'twitter:card' , content: 'summary_large_image' }
]);
}
ngOnDestroy () {
// Clean up meta tags when component is destroyed
this . meta . removeTag ( 'name="description"' );
this . meta . removeTag ( 'property="og:title"' );
}
}
DomSanitizer
Service for sanitizing values to prevent Cross-Site Scripting (XSS) attacks. Provides methods to sanitize or bypass sanitization for trusted content.
@ Injectable ({ providedIn: 'root' })
abstract class DomSanitizer {
abstract sanitize ( context : SecurityContext , value : SafeValue | string | null ) : string | null
abstract bypassSecurityTrustHtml ( value : string ) : SafeHtml
abstract bypassSecurityTrustStyle ( value : string ) : SafeStyle
abstract bypassSecurityTrustScript ( value : string ) : SafeScript
abstract bypassSecurityTrustUrl ( value : string ) : SafeUrl
abstract bypassSecurityTrustResourceUrl ( value : string ) : SafeResourceUrl
}
Security Contexts:
SecurityContext.HTML - HTML content
SecurityContext.STYLE - CSS styles
SecurityContext.SCRIPT - JavaScript code
SecurityContext.URL - URLs in hyperlinks or images
SecurityContext.RESOURCE_URL - URLs for loading executable code
Methods:
sanitize
(context: SecurityContext, value: SafeValue | string | null) => string | null
Sanitizes a value for use in the specified security context.
bypassSecurityTrustHtml
(value: string) => SafeHtml
Marks HTML as trusted. WARNING: Only use with trusted content to avoid XSS vulnerabilities.
bypassSecurityTrustStyle
(value: string) => SafeStyle
Marks CSS as trusted. WARNING: Only use with trusted content.
bypassSecurityTrustScript
(value: string) => SafeScript
Marks JavaScript as trusted. WARNING: Only use with trusted content.
bypassSecurityTrustUrl
(value: string) => SafeUrl
Marks a URL as trusted. WARNING: Only use with trusted URLs.
bypassSecurityTrustResourceUrl
(value: string) => SafeResourceUrl
Marks a resource URL as trusted. WARNING: Only use with trusted resource URLs.
Example:
import { Component , inject } from '@angular/core' ;
import { DomSanitizer , SafeHtml } from '@angular/platform-browser' ;
@ Component ({
selector: 'app-content' ,
template: '<div [innerHTML]="trustedHtml"></div>'
})
export class ContentComponent {
private sanitizer = inject ( DomSanitizer );
trustedHtml : SafeHtml ;
ngOnInit () {
// User-generated content that needs sanitization
const userContent = '<p>Hello <script>alert("XSS")</script></p>' ;
// Angular automatically sanitizes by default
// For trusted content from a safe source:
const trustedContent = '<p>Safe <strong>HTML</strong> from trusted source</p>' ;
this . trustedHtml = this . sanitizer . bypassSecurityTrustHtml ( trustedContent );
}
}
Only bypass sanitization for content you completely trust. Never bypass sanitization for user-generated content or data from external sources. This can expose your application to XSS attacks.
Sanitizing URLs:
import { Component , inject } from '@angular/core' ;
import { DomSanitizer , SafeUrl } from '@angular/platform-browser' ;
@ Component ({
selector: 'app-link' ,
template: '<a [href]="safeUrl">Download</a>'
})
export class LinkComponent {
private sanitizer = inject ( DomSanitizer );
safeUrl : SafeUrl ;
ngOnInit () {
// Bypass sanitization for a trusted blob URL
const blobUrl = URL . createObjectURL ( new Blob ([ 'data' ], { type: 'text/plain' }));
this . safeUrl = this . sanitizer . bypassSecurityTrustUrl ( blobUrl );
}
}
Hydration
provideClientHydration
Configures client-side hydration for applications using server-side rendering (SSR). Hydration improves initial load performance by reusing server-rendered DOM.
function provideClientHydration (
... features : HydrationFeature < HydrationFeatureKind >[]
) : EnvironmentProviders
Optional hydration features to enable (event replay, i18n support, etc.).
Available Features:
withEventReplay() - Replays user events that occurred before hydration completed
withI18nSupport() - Enables hydration for internationalized content
withNoHttpTransferCache() - Disables HTTP response caching between server and client
withHttpTransferCacheOptions(options) - Configures HTTP transfer cache
withIncrementalHydration() - Enables incremental hydration for better performance
Example:
import { bootstrapApplication } from '@angular/platform-browser' ;
import { provideClientHydration , withEventReplay } from '@angular/platform-browser' ;
import { AppComponent } from './app.component' ;
bootstrapApplication ( AppComponent , {
providers: [
provideClientHydration (
withEventReplay ()
)
]
});
Client-side hydration requires server-side rendering to be configured. See @angular/platform-server for SSR setup.
Utilities
provideProtractorTestingSupport
Provides testability support for applications using Protractor or other testing tools that rely on Angular’s testability APIs.
function provideProtractorTestingSupport () : Provider []
Example:
import { bootstrapApplication } from '@angular/platform-browser' ;
import { provideProtractorTestingSupport } from '@angular/platform-browser' ;
import { AppComponent } from './app.component' ;
bootstrapApplication ( AppComponent , {
providers: [
provideProtractorTestingSupport ()
]
});
Utility class for creating platform-agnostic DOM selectors in tests.
class By {
static css ( selector : string ) : Predicate < DebugElement >
static directive ( type : Type < any >) : Predicate < DebugElement >
static all () : Predicate < DebugElement >
}
Example:
import { ComponentFixture , TestBed } from '@angular/core/testing' ;
import { By } from '@angular/platform-browser' ;
import { DebugElement } from '@angular/core' ;
describe ( 'MyComponent' , () => {
let fixture : ComponentFixture < MyComponent >;
beforeEach (() => {
fixture = TestBed . createComponent ( MyComponent );
});
it ( 'should find element by CSS selector' , () => {
const button : DebugElement = fixture . debugElement . query ( By . css ( 'button' ));
expect ( button ). toBeTruthy ();
});
it ( 'should find element by directive' , () => {
const element : DebugElement = fixture . debugElement . query ( By . directive ( MyDirective ));
expect ( element ). toBeTruthy ();
});
});
@angular/platform-server Server-side rendering APIs
@angular/core Core Angular APIs
Router Application routing
HttpClient HTTP communication