Q. Why we need compilation? Ans. We need compilation for achieving higher level of efficiency of our Angular applications.
Take a look at the following example,
// ...
compile: function (el, scope) {
var dirs = this._getElDirectives(el);
var dir;
var scopeCreated;
dirs.forEach(function (d) {
dir = Provider.get(d.name + Provider.DIRECTIVES_SUFFIX);
if (dir.scope && !scopeCreated) {
scope = scope.$new();
scopeCreated = true;
}
dir.link(el, scope, d.value);
});
Array.prototype.slice.call(el.children).forEach(function (c) {
this.compile(c, scope);
}, this);
},
// ...
Using the code above to render the template,
<ul>
<li *ngFor="let name of names"></li>
</ul>
Is much slower compared to:
// ...
this._text_9 = this.renderer.createText(this._el_3, '\n', null);
this._text_10 = this.renderer.createText(parentRenderNode, '\n\n', null);
this._el_11 = this.renderer.createElement(parentRenderNode, 'ul', null);
this._text_12 = this.renderer.createText(this._el_11, '\n ', null);
this._anchor_13 = this.renderer.createTemplateAnchor(this._el_11, null);
this._appEl_13 = new import2.AppElement(13, 11, this, this._anchor_13);
this._TemplateRef_13_5 = new import17.TemplateRef_(this._appEl_13, viewFactory_HomeComponent1);
this._NgFor_13_6 = new import15.NgFor(this._appEl_13.vcRef, this._TemplateRef_13_5, this.parentInjector.get(import18.IterableDiffers), this.ref);
// ...
Flow of events with Ahead-of-Time Compilation
In contrast, with AoT we get through the following steps:
Although the above process seems lightly more complicated the user goes only through the steps:
As you can see the third step is missing which means faster/better UX and on top of that tools like angular2-seed and angular-cli will automate the build process dramatically.
I hope it might help you! Thank you!