Skip to main content

@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.
Experimental APIAll 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.

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

npm install @angular/compiler

Key Features

Template Compilation

The compiler transforms Angular templates into efficient render instructions:
@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() { }
}

Expression Parser

Parses Angular template expressions and bindings:
import { Parser } from '@angular/compiler';

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

i18n Support

Provides internationalization capabilities for templates:
import { I18NHtmlParser } from '@angular/compiler';

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

Core APIs

Compiler Configuration

CompilerConfig
class
Configuration options for the Angular compiler

Template Parser

parseTemplate()
function
Parses an Angular template into an Abstract Syntax Tree (AST)
import { parseTemplate } from '@angular/compiler';

const result = parseTemplate(templateSource, templateUrl, {
  preserveWhitespaces: false,
  interpolationConfig: { start: '{{', end: '}}' }
});

Expression Parser

Parser
class
Parses Angular expressions in templates
import { Parser, Lexer } from '@angular/compiler';

const parser = new Parser(new Lexer());
const ast = parser.parseBinding('user.name', null, 0);

Metadata Types

Component Metadata

The compiler works with component metadata to generate code:
interface CompileComponentMetadata {
  selector: string;
  template: string | null;
  templateUrl: string | null;
  styles: string[];
  styleUrls: string[];
  animations: any[];
  changeDetection: ChangeDetectionStrategy;
  viewEncapsulation: ViewEncapsulation;
}

View Encapsulation

Emulated

Emulate Shadow DOM using prefixed CSS (default)

ShadowDom

Use native Shadow DOM encapsulation

None

No style encapsulation

Compilation Modes

Ahead-of-Time (AOT)

Compiles templates during the build process:
1

Template Analysis

Parse and analyze component templates
2

Code Generation

Generate optimized JavaScript code
3

Tree Shaking

Remove unused code during bundling
4

Runtime

Execute pre-compiled code in the browser

Just-in-Time (JIT)

Compiles templates in the browser at runtime:
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:
  • 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

Render3 Compiler

The modern Ivy compiler (Render3):
import { compileComponentFromMetadata } from '@angular/compiler';

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

Output AST

Low-level code generation AST:
import {
  Expression,
  Statement,
  LiteralExpr,
  InvokeFunctionExpr
} from '@angular/compiler';

// Used for generating JavaScript output code

Schema and Validation

DOM Security Schema

The compiler includes a security schema to prevent XSS attacks by validating property bindings and sanitizing values.
import { SECURITY_SCHEMA } from '@angular/compiler';

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

Element Schema Registry

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

import { Serializer } from '@angular/compiler';

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

Message ID Generation

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:
import { ConstantPool } from '@angular/compiler';

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

Best Practices

Use AOT Compilation

Always use AOT compilation for production builds to get smaller bundles and better performance

Avoid Direct Usage

Avoid using compiler APIs directly unless building Angular tooling

Type Safety

Enable strict template checking for better type safety

Template Analysis

Use the Angular Language Service for template analysis during development

@angular/compiler-cli

Command-line interface for the Angular compiler

@angular/platform-browser-dynamic

JIT compilation support for browsers

Resources

Angular Compiler Guide

Learn about AOT compilation

Template Syntax

Template syntax reference

View Encapsulation

Component styling and encapsulation

i18n Guide

Internationalization documentation

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

Version CompatibilityThis documentation reflects the latest stable version of Angular. API signatures and behavior may vary between versions.