> ## 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/compiler

> Angular Compiler API - Template compilation and code generation for Angular applications

# @angular/compiler

The Angular compiler package provides APIs for compiling Angular templates and components into executable JavaScript code. This package is primarily used internally by the Angular framework and build tools.

<Warning>
  **Experimental API**

  All compiler APIs are currently considered experimental and private. The APIs in this package are subject to change. Avoid relying on them directly in production applications.
</Warning>

## Overview

The `@angular/compiler` package handles the transformation of Angular templates, components, and decorators into optimized JavaScript code that can be executed by the browser. It includes:

* Template parsing and compilation
* Expression parsing and evaluation
* Code generation for Ahead-of-Time (AOT) compilation
* Just-in-Time (JIT) compilation support
* Internationalization (i18n) support
* Style encapsulation

## Installation

```bash theme={null}
npm install @angular/compiler
```

## Key Features

### Template Compilation

The compiler transforms Angular templates into efficient render instructions:

<CodeGroup>
  ```typescript Component Template theme={null}
  @Component({
    selector: 'app-example',
    template: `
      <div *ngIf="isVisible">
        <h1>{{ title }}</h1>
        <button (click)="handleClick()">Click me</button>
      </div>
    `
  })
  export class ExampleComponent {
    title = 'Hello';
    isVisible = true;
    handleClick() { }
  }
  ```

  ```typescript Compiled Output theme={null}
  // Simplified compiled output
  function ExampleComponent_Template(rf, ctx) {
    if (rf & 1) {
      // Creation mode
      element(0, "div");
      element(1, "h1");
      element(2, "button");
      listener("click", function() { return ctx.handleClick(); });
    }
    if (rf & 2) {
      // Update mode
      advance(1);
      textInterpolate(ctx.title);
    }
  }
  ```
</CodeGroup>

### Expression Parser

Parses Angular template expressions and bindings:

```typescript theme={null}
import { Parser } from '@angular/compiler';

// Parses expressions like: {{ user.name | uppercase }}
// Used internally by the template compiler
```

### i18n Support

Provides internationalization capabilities for templates:

```typescript theme={null}
import { I18NHtmlParser } from '@angular/compiler';

// Extracts and manages translatable content
// Supports message extraction and replacement
```

## Core APIs

### Compiler Configuration

<ParamField path="CompilerConfig" type="class">
  Configuration options for the Angular compiler

  <Expandable title="properties">
    <ParamField path="defaultEncapsulation" type="ViewEncapsulation">
      Default view encapsulation strategy (Emulated, ShadowDom, or None)
    </ParamField>

    <ParamField path="preserveWhitespaces" type="boolean">
      Whether to preserve whitespaces in templates
    </ParamField>

    <ParamField path="strictInjectionParameters" type="boolean">
      Enable strict dependency injection parameter checking
    </ParamField>
  </Expandable>
</ParamField>

### Template Parser

<ParamField path="parseTemplate()" type="function">
  Parses an Angular template into an Abstract Syntax Tree (AST)

  ```typescript theme={null}
  import { parseTemplate } from '@angular/compiler';

  const result = parseTemplate(templateSource, templateUrl, {
    preserveWhitespaces: false,
    interpolationConfig: { start: '{{', end: '}}' }
  });
  ```
</ParamField>

### Expression Parser

<ParamField path="Parser" type="class">
  Parses Angular expressions in templates

  ```typescript theme={null}
  import { Parser, Lexer } from '@angular/compiler';

  const parser = new Parser(new Lexer());
  const ast = parser.parseBinding('user.name', null, 0);
  ```
</ParamField>

## Metadata Types

### Component Metadata

The compiler works with component metadata to generate code:

```typescript theme={null}
interface CompileComponentMetadata {
  selector: string;
  template: string | null;
  templateUrl: string | null;
  styles: string[];
  styleUrls: string[];
  animations: any[];
  changeDetection: ChangeDetectionStrategy;
  viewEncapsulation: ViewEncapsulation;
}
```

### View Encapsulation

<CardGroup cols={3}>
  <Card title="Emulated" icon="circle-half-stroke">
    Emulate Shadow DOM using prefixed CSS (default)
  </Card>

  <Card title="ShadowDom" icon="shield">
    Use native Shadow DOM encapsulation
  </Card>

  <Card title="None" icon="circle-xmark">
    No style encapsulation
  </Card>
</CardGroup>

## Compilation Modes

### Ahead-of-Time (AOT)

Compiles templates during the build process:

<Steps>
  <Step title="Template Analysis">
    Parse and analyze component templates
  </Step>

  <Step title="Code Generation">
    Generate optimized JavaScript code
  </Step>

  <Step title="Tree Shaking">
    Remove unused code during bundling
  </Step>

  <Step title="Runtime">
    Execute pre-compiled code in the browser
  </Step>
</Steps>

### Just-in-Time (JIT)

Compiles templates in the browser at runtime:

```typescript theme={null}
import { CompilerFacadeImpl } from '@angular/compiler';

// JIT compilation happens automatically in development mode
// Uses the compiler facade to compile components on-demand
```

## Advanced Features

### Template AST

The compiler generates multiple AST representations:

<Accordion title="Template AST Nodes">
  * **Element**: HTML elements (`<div>`, `<span>`, etc.)
  * **Text**: Text content and interpolations
  * **BoundAttribute**: Property bindings `[property]="value"`
  * **BoundEvent**: Event bindings `(event)="handler()"`
  * **Reference**: Template references `#ref`
  * **Variable**: Template variables `let item`
  * **DeferredBlock**: Deferrable views `@defer`
  * **IfBlock**: Conditional blocks `@if`
  * **ForLoopBlock**: Loop blocks `@for`
  * **SwitchBlock**: Switch blocks `@switch`
</Accordion>

### Render3 Compiler

The modern Ivy compiler (Render3):

```typescript theme={null}
import { compileComponentFromMetadata } from '@angular/compiler';

// Compiles component metadata to Ivy instructions
// Generates ɵcmp definition factory
```

### Output AST

Low-level code generation AST:

```typescript theme={null}
import {
  Expression,
  Statement,
  LiteralExpr,
  InvokeFunctionExpr
} from '@angular/compiler';

// Used for generating JavaScript output code
```

## Schema and Validation

### DOM Security Schema

<Note>
  The compiler includes a security schema to prevent XSS attacks by validating property bindings and sanitizing values.
</Note>

```typescript theme={null}
import { SECURITY_SCHEMA } from '@angular/compiler';

// Validates that bindings are safe
// Identifies properties that require sanitization
```

### Element Schema Registry

```typescript theme={null}
import { DomElementSchemaRegistry } from '@angular/compiler';

const registry = new DomElementSchemaRegistry();

// Check if a property exists on an element
const hasProperty = registry.hasProperty('div', 'hidden', []);

// Get the security context for a property
const securityContext = registry.securityContext('div', 'innerHTML', true);
```

## Internationalization (i18n)

### Message Extraction

```typescript theme={null}
import { Serializer } from '@angular/compiler';

// Extract translatable messages from templates
// Generate translation files (XLIFF, XMB, etc.)
```

### Message ID Generation

```typescript theme={null}
import { computeMsgId } from '@angular/compiler';

const messageId = computeMsgId(message, meaning);
// Generates stable IDs for translation messages
```

## Constant Pool

The compiler uses a constant pool to deduplicate and optimize generated code:

```typescript theme={null}
import { ConstantPool } from '@angular/compiler';

const pool = new ConstantPool();
// Manages shared constants in compiled output
// Reduces bundle size through deduplication
```

## Best Practices

<CardGroup cols={2}>
  <Card title="Use AOT Compilation" icon="rocket">
    Always use AOT compilation for production builds to get smaller bundles and better performance
  </Card>

  <Card title="Avoid Direct Usage" icon="triangle-exclamation">
    Avoid using compiler APIs directly unless building Angular tooling
  </Card>

  <Card title="Type Safety" icon="check">
    Enable strict template checking for better type safety
  </Card>

  <Card title="Template Analysis" icon="magnifying-glass">
    Use the Angular Language Service for template analysis during development
  </Card>
</CardGroup>

## Related Packages

<CardGroup cols={2}>
  <Card title="@angular/compiler-cli" icon="terminal">
    Command-line interface for the Angular compiler
  </Card>

  <Card title="@angular/platform-browser-dynamic" icon="browser">
    JIT compilation support for browsers
  </Card>
</CardGroup>

## Resources

<CardGroup cols={2}>
  <Card title="Angular Compiler Guide" icon="book" href="https://angular.dev/tools/cli/aot-compiler">
    Learn about AOT compilation
  </Card>

  <Card title="Template Syntax" icon="code" href="https://angular.dev/guide/templates">
    Template syntax reference
  </Card>

  <Card title="View Encapsulation" icon="shield" href="https://angular.dev/concepts/components/styling">
    Component styling and encapsulation
  </Card>

  <Card title="i18n Guide" icon="globe" href="https://angular.dev/guide/i18n">
    Internationalization documentation
  </Card>
</CardGroup>

## Exports Reference

### Core Exports

* `core` - Core compiler utilities
* `outputAst` - Output AST for code generation
* `CompilerConfig` - Compiler configuration
* `ConstantPool` - Constant pool management

### Template Parsing

* `parseTemplate()` - Template parser
* `makeBindingParser()` - Binding parser factory
* `TmplAst*` - Template AST node types

### Expression Parsing

* `Parser` - Expression parser
* `Lexer` - Expression lexer
* `AST` - Expression AST types

### Code Generation

* `compileComponentFromMetadata()` - Component compiler
* `compileDirectiveFromMetadata()` - Directive compiler
* `compileNgModule()` - NgModule compiler
* `compilePipeFromMetadata()` - Pipe compiler

### Render3 (Ivy)

* `R3Identifiers` - Ivy runtime identifiers
* `R3*Metadata` - Metadata types for compilation
* Compilation functions for declarations

### Schema & Validation

* `SECURITY_SCHEMA` - DOM security schema
* `DomElementSchemaRegistry` - Element schema registry
* `CUSTOM_ELEMENTS_SCHEMA` - Custom elements schema
* `NO_ERRORS_SCHEMA` - Disable schema validation

### Internationalization

* `I18NHtmlParser` - i18n HTML parser
* `Serializer` - Message serializers
* `computeMsgId()` - Message ID generation

***

<Info>
  **Version Compatibility**

  This documentation reflects the latest stable version of Angular. API signatures and behavior may vary between versions.
</Info>
