> ## Documentation Index
> Fetch the complete documentation index at: https://mintlify.com/angular/angular/llms.txt
> Use this file to discover all available pages before exploring further.

# @angular/platform-browser

> Platform APIs for running Angular applications in a web browser

## 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.

```typescript theme={null}
function bootstrapApplication(
  rootComponent: Type<unknown>,
  options?: ApplicationConfig,
  context?: BootstrapContext
): Promise<ApplicationRef>
```

<ParamField path="rootComponent" type="Type<unknown>" required>
  A standalone component to render as the application root.
</ParamField>

<ParamField path="options" type="ApplicationConfig">
  Configuration object containing providers and other application settings.
</ParamField>

<ParamField path="context" type="BootstrapContext">
  Optional context providing a pre-existing platform injector (useful for server-side rendering).
</ParamField>

**Returns:** `Promise<ApplicationRef>` - The bootstrapped application reference.

**Example:**

```typescript theme={null}
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()
  ]
});
```

<Note>
  The root component must be a standalone component. Use `standalone: true` in the component decorator.
</Note>

### createApplication

Creates an Angular application without bootstrapping any components. Components can be bootstrapped later using the returned `ApplicationRef`.

```typescript theme={null}
function createApplication(
  options?: ApplicationConfig,
  context?: BootstrapContext
): Promise<ApplicationRef>
```

<ParamField path="options" type="ApplicationConfig">
  Configuration object containing providers and other application settings.
</ParamField>

<ParamField path="context" type="BootstrapContext">
  Optional context providing a pre-existing platform injector.
</ParamField>

**Returns:** `Promise<ApplicationRef>` - Application reference for manual component bootstrapping.

**Example:**

```typescript theme={null}
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);
```

### platformBrowser

Creates a browser platform instance. This is typically used for advanced scenarios where you need explicit control over platform creation.

```typescript theme={null}
function platformBrowser(
  extraProviders?: StaticProvider[]
): PlatformRef
```

<ParamField path="extraProviders" type="StaticProvider[]">
  Optional additional platform-level providers.
</ParamField>

**Returns:** `PlatformRef` - Browser platform reference.

**Example:**

```typescript theme={null}
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`.

```typescript theme={null}
@NgModule({
  exports: [CommonModule, ApplicationModule]
})
class BrowserModule {}
```

**Example:**

```typescript theme={null}
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 {}
```

<Warning>
  `BrowserModule` should only be imported once in your root module. Child modules should import `CommonModule` instead.
</Warning>

## Services

### Title

Service for getting and setting the HTML document title.

```typescript theme={null}
@Injectable({ providedIn: 'root' })
class Title {
  getTitle(): string
  setTitle(newTitle: string): void
}
```

**Methods:**

<ParamField path="getTitle" type="() => string">
  Returns the current document title.
</ParamField>

<ParamField path="setTitle" type="(newTitle: string) => void">
  Sets the document title.
</ParamField>

**Example:**

```typescript theme={null}
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');
  }
}
```

### Meta

Service for managing HTML `<meta>` tags. Essential for SEO, social sharing, and security configurations.

```typescript theme={null}
@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:**

```typescript theme={null}
type MetaDefinition = {
  charset?: string
  content?: string
  httpEquiv?: string
  id?: string
  itemprop?: string
  name?: string
  property?: string
  scheme?: string
  url?: string
  [prop: string]: string
}
```

**Methods:**

<ParamField path="addTag" type="(tag: MetaDefinition, forceCreation?: boolean) => HTMLMetaElement | null">
  Adds a meta tag to the document. If `forceCreation` is false (default), returns existing tag if found.
</ParamField>

<ParamField path="addTags" type="(tags: MetaDefinition[], forceCreation?: boolean) => HTMLMetaElement[]">
  Adds multiple meta tags to the document.
</ParamField>

<ParamField path="getTag" type="(attrSelector: string) => HTMLMetaElement | null">
  Retrieves a meta tag using an attribute selector (e.g., `"name='description'"`).
</ParamField>

<ParamField path="getTags" type="(attrSelector: string) => HTMLMetaElement[]">
  Retrieves all meta tags matching the attribute selector.
</ParamField>

<ParamField path="updateTag" type="(tag: MetaDefinition, selector?: string) => HTMLMetaElement | null">
  Updates an existing meta tag or creates one if it doesn't exist.
</ParamField>

<ParamField path="removeTag" type="(attrSelector: string) => void">
  Removes a meta tag matching the attribute selector.
</ParamField>

**Example:**

```typescript theme={null}
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.

```typescript theme={null}
@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:**

<ParamField path="sanitize" type="(context: SecurityContext, value: SafeValue | string | null) => string | null">
  Sanitizes a value for use in the specified security context.
</ParamField>

<ParamField path="bypassSecurityTrustHtml" type="(value: string) => SafeHtml">
  Marks HTML as trusted. **WARNING:** Only use with trusted content to avoid XSS vulnerabilities.
</ParamField>

<ParamField path="bypassSecurityTrustStyle" type="(value: string) => SafeStyle">
  Marks CSS as trusted. **WARNING:** Only use with trusted content.
</ParamField>

<ParamField path="bypassSecurityTrustScript" type="(value: string) => SafeScript">
  Marks JavaScript as trusted. **WARNING:** Only use with trusted content.
</ParamField>

<ParamField path="bypassSecurityTrustUrl" type="(value: string) => SafeUrl">
  Marks a URL as trusted. **WARNING:** Only use with trusted URLs.
</ParamField>

<ParamField path="bypassSecurityTrustResourceUrl" type="(value: string) => SafeResourceUrl">
  Marks a resource URL as trusted. **WARNING:** Only use with trusted resource URLs.
</ParamField>

**Example:**

```typescript theme={null}
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);
  }
}
```

<Warning>
  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.
</Warning>

**Sanitizing URLs:**

```typescript theme={null}
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.

```typescript theme={null}
function provideClientHydration(
  ...features: HydrationFeature<HydrationFeatureKind>[]
): EnvironmentProviders
```

<ParamField path="features" type="HydrationFeature[]">
  Optional hydration features to enable (event replay, i18n support, etc.).
</ParamField>

**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:**

```typescript theme={null}
import { bootstrapApplication } from '@angular/platform-browser';
import { provideClientHydration, withEventReplay } from '@angular/platform-browser';
import { AppComponent } from './app.component';

bootstrapApplication(AppComponent, {
  providers: [
    provideClientHydration(
      withEventReplay()
    )
  ]
});
```

<Note>
  Client-side hydration requires server-side rendering to be configured. See `@angular/platform-server` for SSR setup.
</Note>

## Utilities

### provideProtractorTestingSupport

Provides testability support for applications using Protractor or other testing tools that rely on Angular's testability APIs.

```typescript theme={null}
function provideProtractorTestingSupport(): Provider[]
```

**Example:**

```typescript theme={null}
import { bootstrapApplication } from '@angular/platform-browser';
import { provideProtractorTestingSupport } from '@angular/platform-browser';
import { AppComponent } from './app.component';

bootstrapApplication(AppComponent, {
  providers: [
    provideProtractorTestingSupport()
  ]
});
```

### By

Utility class for creating platform-agnostic DOM selectors in tests.

```typescript theme={null}
class By {
  static css(selector: string): Predicate<DebugElement>
  static directive(type: Type<any>): Predicate<DebugElement>
  static all(): Predicate<DebugElement>
}
```

**Example:**

```typescript theme={null}
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();
  });
});
```

## Related APIs

<CardGroup cols={2}>
  <Card title="@angular/platform-server" icon="server" href="/api/platform/server">
    Server-side rendering APIs
  </Card>

  <Card title="@angular/core" icon="cube" href="/api/core/component">
    Core Angular APIs
  </Card>

  <Card title="Router" icon="route" href="/api/router/router-class">
    Application routing
  </Card>

  <Card title="HttpClient" icon="network-wired" href="/api/http/httpclient">
    HTTP communication
  </Card>
</CardGroup>
