Google News
logo
Angular - Interview Questions
How AOT works in Angular?
The Angular AOT compiler extracts metadata to interpret the parts of the application that Angular is supposed to manage. You can specify the metadata explicitly in decorators such as @Component() and @Input(), or implicitly in the constructor declarations of the decorated classes. The metadata tells Angular how to construct instances of your application classes and interact with them at runtime.
 
In the following example, the @Component() metadata object and the class constructor tell Angular how to create and display an instance of TypicalComponent.
@Component({
  selector: 'app-typical',
  template: '<div>A typical component for {{data.name}}</div>'
})
export class TypicalComponent {
  @Input() data: TypicalData;
  constructor(private someService: SomeService) { … }
}
The Angular compiler extracts the metadata once and generates a factory for TypicalComponent. When it needs to create a TypicalComponent instance, Angular calls the factory, which produces a new visual element, bound to a new instance of the component class with its injected dependency.

Compilation phases  :  There are three phases of AOT compilation.

  Phase Details
1 code analysis In this phase, the TypeScript compiler and AOT collector create a representation of the source. The collector does not attempt to interpret the metadata it collects. It represents the metadata as best it can and records errors when it detects a metadata syntax violation.
2 code generation In this phase, the compiler's StaticReflector interprets the metadata collected in phase 1, performs additional validation of the metadata, and throws an error if it detects a metadata restriction violation.
3 template type checking In this optional phase, the Angular template compiler uses the TypeScript compiler to validate the binding expressions in templates. You can enable this phase explicitly by setting the fullTemplateTypeCheck configuration option; see Angular compiler options.

Metadata restrictions :  You write metadata in a subset of TypeScript that must conform to the following general constraints:
 
* Limit expression syntax to the supported subset of JavaScript
* Only reference exported symbols after code folding
* Only call functions supported by the compiler
* Decorated and data-bound class members must be public
Advertisement