Friday, January 13, 2017

Understanding AOT and Dynamic Components

This is a guest post from Sean Landsman at ag-Grid. Sean is the lead engineer on ag-Grid's Angular integration. -- Stephen Fluin


ag-Grid is an enterprise datagrid that works with Angular. As ag-Grid works with many frameworks, the internals of the grid had to allow for Angular rendering inside the grid despite ag-Grid not being written in Angular itself. This was done using Angular Dynamic Components and we managed to do it while still supporting AOT. This blog details what we learnt along the way.

The Setup

To explain we present a simple sample application that isolates what we are trying to do. In our example below we are going to develop two main Modules - one will be a Library (in our case this was ag-Grid) that will display an array of dynamically created Components (similar to how ag-Grid displays Angular components inside the grid's cells), and the other will be our actual Application.
The end result will be look like this:

You can find all the code for this example over at GitHub, and the live example over at
One further note - when we return to "user" below, we are referring to a user (or client) of the Library we're writing.

The Library

Our Library is going to be a simple one - all it does is display an array of dynamically created Angular Components. The main component looks like this:

    selector: 'grid-component',
    template: `
        <div class="row" *ngFor="let cellComponentType of cellComponentTypes">
            <div class="col-lg-12">
                <grid-cell [componentType]="cellComponentType"></grid-cell>
export class Grid {
    @Input() componentTypes: any;

    cellComponentTypes: any[] = [];

    addDynamicCellComponent(selectedComponentType:any) {

As you can see it's a pretty simple component - all it does is display the current cellComponentTypes. These are the user supplied components, and they can be any Angular Component.

The interesting part of the Library is in the Cell Component:

    selector: 'grid-cell',
    template: ''
export class Cell implements OnInit {
    @Input() componentType: any;

    constructor(private viewContainerRef: ViewContainerRef,
                private cfr: ComponentFactoryResolver) {

    ngOnInit() {
        let compFactory = this.cfr.resolveComponentFactory(this.componentType);

You'll notice that we don't have a template here - that's deliberate as the Cell doesn't have any
    content of its own - all it does is serve up the user supplied Component. The important part of this Component are
    these two lines:

let compFactory = this.cfr.resolveComponentFactory(this.componentType);

This line asks the ComponentFactoryResolver to find the ComponentFactory for the provided
    Component. We'll use this factory next to create the actual component:


And that's all there is to it from the Library Component side of things - we find the factory for the Component, and
    then create a new instance of the Component. Easy!

For this to work we need to tell Angular's AOT Compiler to create factories for the user provided Components, or ComponentFactoryResolver won't find them. We can make use of NgModule.entryComponents for this - this will ensure that the AOT compiler creates the necessary factories, but for you purposes there is an easier way, especially from a users perspective:

    imports: [
    declarations: [
    exports: [
export class GridModule {
    static withComponents(components: any[]) {
        return {
            ngModule: GridModule,
            providers: [
                {provide: ANALYZE_FOR_ENTRY_COMPONENTS, useValue: components, multi: true}

By making use of ANALYZE_FOR_ENTRY_COMPONENTS here, we are able to add multiple components to the NgModule.entryComponents
    entry dynamically, in a user friendly way.

The Application

From the application side of things, the first thing we need to do is create the components we want to use in the Library - these can be any valid Angular Component. In our case we have three similar Components:

    selector: 'dynamic-component',
    template: '<div class="img-rounded" style="background-color: lightskyblue;margin: 5px"> Blue Dynamic Component! </div>',
export class BlueDynamicComponent {

All these components do is display a little styled text.
To register these in both our Application, and in the Library, we need to switch to the Application Module:

    imports: [
    declarations: [
    bootstrap: [AppComponent]
export class AppModule {

We declare our Components in the usual way, but we additionally need to register them with the Library (remember,
    this is the part where they'll be added to the
    Library's NgModule.entryComponent entry). We do this in this part of the module:


Finally, we can take a look at the main Application Component:

    selector: 'my-app',
    template: `
        <div class="container-fluid">
            <div class="page-header">
                <h1>Creating AOT Friendly Dynamic Components with Angular
            <div class="row">
                <div class="col-lg-12">
                    <div class="panel panel-default">
                        <div class="panel-heading">Application Code</div>
                        <div class="panel-body">
                            <div class="input-group">
                                <span class="input-group-btn">
                                    <button type="button" class="btn btn-primary" (click)="grid.addDynamicCellComponent(selectedComponentType)">Add Dynamic Grid component

                                <select class="form-control" [(ngModel)]="selectedComponentType">
                                    <option *ngFor="let cellComponentType of componentTypes" [ngValue]="cellComponentType">{{}}
            <div class="row">
                <div class="col-lg-12">
                    <div class="panel panel-default">
                        <div class="panel-heading">Library Code</div>
                        <div class="panel-body">
                            <grid-component #grid></grid-component>
export class AppComponent implements OnInit {
    @Input() componentTypes: any[] = [BlueDynamicComponent, GreenDynamicComponent, RedDynamicComponent];
    @Input() selectedComponentType: any;

    ngOnInit(): void {
        // default to the first available option
        this.selectedComponentType = this.componentTypes ? this.componentTypes[0] : null;

It may look like theres a lot going on here, but the bulk of the template is to make it look pretty. The key parts of this Component are:

<button type="button" class="btn btn-primary" (click)="grid.addDynamicCellComponent(selectedComponentType)">Add Dynamic Grid component

This will ask the Library to add a create a new instance of the supplied Component, and in turn render it.

<grid-component #grid></grid-component>

And this line is our Library Component.

That's it - easy to write and use (from both an Application and Library perspective), and AOT (and JIT!) friendly.

Benefits of using AOT

The speed and size of the resulting application when using AOT can be significant. In our ag-grid-ng2-example project, we estimate the size of the resulting application went from 3.9Mb down to 2.4Mb - a reduction of just under 40%, without optimising for size or being particularly aggressive with rollup.

Speed-wise, the loading time when using AOT is significantly more responsive on startup - this makes sense given that Angular doesn't have to compile all the code once again. Take a look at the examples project and try both the JIT and AOT versions out for yourself!

There's so much more you can do if you decide to combine Angular Components with ag-Grid - powerful functionality, fast grid and easy configuration. What are you waiting for?!

Thursday, December 22, 2016

Angular Material Beta Release, New Flex-Layout library

We're sneaking in a little holiday gift at the end of the year: two new beta releases for developers to try out with the latest version of Angular.

material components with a custom theme and RTL text

In March, we gave you a first preview of the new Angular Material components. Today's beta release of @angular/material includes 22 UI components written for the latest Angular: button, button‑toggle, card‑list, chips, checkbox, dialog, grid‑list, icon, input, menu, progress‑bar, progress‑spinnerradio‑buttonselectsidenavslide‑toggleslidersnackbartextareatoolbar, and tooltip. It also provides support for accessibility, custom themes, and RTL text.  For documentation and examples, see

Also out in beta today, the new @angular/flex-layout package is a general-purpose flex-based layout library for use in any Angular application later than version 2.4. It provides a responsive engine and API to easily define how UI layouts should update as viewport sizes change with orientation across different display devices. The HTML API makes it trivial to quickly arrange (and auto-resize) web page component layouts. In Angular 1.x, layout tools were included as part of Angular Material. With flex-layout, we have made layout a standalone library, decoupled from the UI components. Learn more about the flex-layout beta here.

Whether you're building a new app, or upgrading from a legacy Angular 1.x app that needs Layout and Angular Material APIs, these components will help you to quickly build a beautiful and performant UI consistent with Google's Material Design spec.

What does beta mean?

We've built all of the core UI components that most applications will need. Start using these libraries, and give us feedback on GitHub.

We don’t plan to make any large API changes before exiting beta, however we’ll make changes based on feedback we receive during the beta process.

What's still in the works?

For Angular Material, developers can expect other advanced components (e.g. data-table, date-picker), and typography support. Both libraries will see ongoing bug fixes and feature improvements.
For users on Angular Material 1.x, a new release is expected in early 2017 with bug fixes and security improvements.

Tuesday, December 20, 2016

Angular 2.4.0 Now Available

Angular version 2.4.0 - stability-interjection - is now available. This is a minor release following our announced adoption of Semantic Versioning, meaning that it contains no breaking changes and that it is a drop-in replacement for 2.x.x.

What's new?
    • This release updates our dependencies to the recently announced RxJS 5 stable

For the complete list of features and bugfixes please see the changelog.

Tuesday, December 13, 2016

Ok... let me explain: it's going to be Angular 4.0, or just Angular

This is a guest blog post by Juri Strumpflohner. Juri is a full-stack developer, architect and tech lead with a passion for frontend development, especially Angular. Juri writes technical articles on his personal blog and is the author of some online video courses. He also likes to engage and help the Angular community on Twitter, so follow him for more interesting news and articles around Angular and frontend web development. Juri was an attendee of NG-BE, Belgium’s first Angular conference last week and did a better job covering our announcements than we would have done, so we are cross-posting his blog post here.

At the 8th and 9th of December 2016 was NG-BE, Belgium’s first Angular conference. Igor Minar (Angular lead dev) attended as the keynote speaker with some interesting announcements regarding Angular’s release schedule. Please read the entire post, there are a couple of important things.

Igor was extremely open and transparent about the announcement and even about the way of presenting it. He basically created the presentation openly the day before the conference:

So here it is:

Angular 4, March 2017, Backwards Compatible w/ Angular 2

Why Angular 4?? Why even Angular 3?? What is going on?

Angular uses SEMVER

Back in September when the new Angular was finally released, the Angular team also announced they will switch to Semantic Versioning (SEMVER).

As the name already explains, Semantic Versioning is all about adding meaning to version numbers. This allows developers to not only reason about any upgrade we do, but we can even let tools such as NPM do it in a automatic and safe manner for us.

A semantic version consists of three numbers:

2.3.1 - major = breaking change, minor = new features, not breaking, patch = bugfixes, not breaking

Whenever you fix a bug and release it, you increase the last number, if a new feature is added, you increase the second number and whenever you release a breaking change you increase the first number.

“A breaking change happens whenever you as a developer and consumer of a library, have to step in and adjust your code after a version upgrade.”

So what does this mean for the Angular team? As with every evolving piece of software, breaking changes will occur at some point. For example, giving a compiler error for existing application bugs that went unnoticed with the previous compiler version, anything, that will break an existing application when upgrading Angular, requires the team to bump the major version number.

Just to be clear, as also Igor mentioned in his talk. Right now, even just upgrading Angular’s TypeScript dependency from v1.8 to v2.1 or v2.2 and compile Angular with it, would technically cause a breaking change. So they’re taking SEMVER very, very seriously.

Breaking changes don’t have to be painful!

People that have been following the Angular community for a while, definitely know what I’m talking about. We went from Angular 1 to Angular 2, and it was a total breaking change, with new APIs, new patterns. That was obvious: ultimately Angular 2 was a complete rewrite. (Even though there are upgrade options for you available)

Changing from version 2 to version 4, 5, … won’t be like changing from Angular 1. It won’t be a complete rewrite, it will simply be a change in some core libraries that demand a major SEMVER version change. Also, there will be proper deprecation phases to allow developers to adjust their code.

Internally at Google, the Angular team uses a tool for handling automatic upgrades, even of breaking changes. This is still something that has to be planned in more detail, but the team is working hard on making this tool generally available, most probably in 2017 in time for Angular 5.

It’s just “Angular”

As you might have already guessed, the term “Angular 2” is also kind of deprecated once we get to version 4, 5 etc. That said, we should start naming it simply “Angular” without the version suffix.

“It’s just #angular”

Also, we should start avoiding GitHub/NPM libraries prefixed with ng2- or angular2-.

Naming guidelines

Basically from now on, name all versions of Angular simply “Angular”. Try to avoid using the version number, unless it is really necessary to disambiguate.

Three simple guidelines:

  • Use “Angular” by default (e.g. “I’m an Angular developer”, “This is an Angular meetup”, “The Angular ecosystem is growing quickly”)
  • Use “Angular 1”, “Angular 2”, “Angular 4” when talking about a specific release train (e.g. when talking about a newly introduced feature - “This is an introduction to feature X, introduced in Angular 4”, “We are upgrading from Angular 1 to Angular 2”, “I’m proposing this change for Angular 5”)
  • Use full semver version when reporting a bug (e.g. “This issue is present as of Angular 2.3.1”)

All the docs - even for Angular 1 - will be aligned to this in the coming weeks. Yes, they'll be dropping "JS" from AngularJS where possible. Also in blog articles, courses, books or whenever you are targeting a very specific version of Angular, consider adding a header line which states that:

“This article uses Angular v2.3.1.”

That helps avoid confusion for your readers, especially when you are writing about specific APIs.

Why not version 3 then?

The core Angular libraries live in one single GitHub repository at All of them are versioned the same way, but distributed as different NPM packages:

@angular/core v2.3.0, @angular/compiler v2.3.0, @angular/compiler-cli v2.3.0, @angular/http v2.3.0, in bold: @angular/router v3.3.0

Due to this misalignment of the router package’s version, the team decided to go straight for Angular v4. In this way again, all the core packages are aligned which will be easier to maintain and help avoid confusion in the future.

Also it is important to understand how Angular is being used and integrated inside Google (Igor speaks about this here in his keynote). All Google applications use Angular version equal to the current GitHub’s master branch of the Angular repository. Whenever a new commit lands in master, it will be integrated into Google’s single, giant mono-repo, where also other products such as Maps, Adsense etc. live. As a consequence all of the projects using Angular internally at Google will run their extensive test suites against this new version. This makes the team very confident to cut a new release, since it will contain the exact combination of versions of Angular packages that have been already battle tested inside Google. Thus, having aligned versions totally makes sense and makes it easier to maintain them over time, which in turn helps the team be more productive in releasing new features.

Tentative release schedule

The fact that breaking changes will arrive, doesn’t mean they will arrive every other week. The Angular team committed to time based releases that occur in three cycles:

  • patch releases every week,
  • 3 monthly minor release after each major release and
  • a major release with easy-to-migrate-over breaking changes every 6 months.

The next 3 months will be dedicated to finalizing Angular 4.0.0.

Weekly breakdown of all releases starting with 4.0.0-beta.0, ending with 4.0.0 on March 1, 2017

After Angular 4.0.0, this will be the tentative schedule for further releases:

Version 4 in March 2017, Version 5 in September/October 2017, Version 6 in March 2018, Version 7 in September/October 2018

Video: See the announcement yourself


There are two main important messages here:

  • don’t worry about version numbers
  • we do need to evolve Angular in order to avoid another Angular 1 to Angular 2 change, but we should do it together as a community in a transparent, predictable and incremental way.

Also, I’d like to thank Igor for being so open at presenting this data, especially since he knows what a sensitive topic breaking changes are and have been in the past. This means a lot and I hope that the community will realize why all these changes are good for everyone involved.

Thursday, December 8, 2016

Angular 1.6.0 released

AngularJS 1.6.0 - rainbow-tsunami

Release Announcement

Continuing our development and support of Angular 1, we are announcing the next significant release, 1.6.0, which has been in development since May this year.

In this release we have added a number of useful features that should improve the developer experience and we have tightened up the security of Angular 1 even further. We have also removed a handful of deprecated features that makes the codebase easier to maintain and in many cases improves performance.

New Features

Here are the most significant new features available in 1.6.0. Check out the changelog for more detail.

Inheriting ngModelOptions

When defining model options using the ngModelOptions directive, you can now choose to inherit options from ancestor ngModelOptions directives. This means that developers can centralise common model options rather than repeating themselves across all their HTML.

You can see examples of what you can do with this new feature in Todd Motto's recent blog post.

Alignment with jQuery 3

jQuery 3 was released in June this year and contains some changes that left our own jqLite implementation out of sync. In this release we have changed jqLite so that it matches the behaviour of jQuery 3.

Controller binding pre-assignment

We no longer pre-assign bindings onto instances of directive controllers before calling their constructors. This behaviour was not in keeping with how JavaScript object instantiation works and also prevented developers from using native JavaScript classes where available.

Now all directive controllers should use $onInit to initialize their state, where the bindings are guaranteed to be ready. This is also closer to the semantic of Angular 2 components.

Todd Motto has written about how to handle this change in a recent blog post.

Support for non-string select options

With improved support for non-string values in option elements, you can now render most select option use cases using ngRepeat and ngValue, rather than having to resort to ngOptions.

In other words, as shown in this Plunker, rather than this:

  ng-options="x as disable when !x.enabled for x in $ctrl.options">
  <option value="">Empty Option</option>

you can now write:

<select ng-model="$ctrl.value">
  <option ng-value="null">Empty Option</option>
    ng-repeat="x in $ctrl.options"

This results in clearer Angular 1 templates and is more in keeping with how it is done in Angular 2.

Better support for range inputs

In Angular 1.5.x (from 1.5.10 and later) you need to manually opt-in to this support since the behaviour of native range inputs required a change to how ngModel handled updates to the value:

Angular 1.6 now fully supports <input type=range ng-model="..."> by default without having to opt-in.

  • It requires the model to be a number, and will set the model to a number.
  • It only supports setting minimum and maximum values via the min/max attributes.
  • It follows the browser behavior of never allowing an invalid value: when the browser converts an invalid value to a valid value, the the model is set to this new valid value.

Security Improvements

There have been a number of commits that have improved or clarified the security of Angular 1 applications. Here are some of the highlights.

Mozilla Addons

Due to some strengthening work we have done to make it more difficult to autobootstrap Angular in browser extensions, all versions of Angular from 1.5.9/1.6.0 onwards are now whitelisted as safe to use in Mozilla Addons.

Expression sandbox removal

In this version of Angular we have removed the Angular expression sandbox feature. Some developers were incorrectly using this in an attempt to prevent XSS attacks to their templates. To make it clear that this should not be relied upon in this way we have made the decision to remove it completely. A more detailed write up of the background, the decision and whether you need to do anything can be found in our previous blog post.


JSONP is now secured by the $sce service, in the same way that other significant resources are in Angular 1. JSONP URLs must now be whitelisted or explicitly trusted before Angular will allow a request to the end point. Further the syntax for JSONP URLs is now more secure, by disallowing the JSON_CALLBACK from the URL template and requiring that the callback is provided via the jsonpCallbackParam config param for requests.

Other Changes

There are over 70 significant commits between 1.5 and 1.6. You can find a detailed list of all the changes, including bug fixes and performance improvements in our changelog.

Migrating from 1.5 to 1.6

While there are a number of breaking changes between 1.5 and 1.6, many only affect very rare corner cases. There are a few significant changes that you should be aware of and we have a comprehensive migration guide to ensure that your migration goes smoothly.

Previous Version Support

We believe that Angular 1.6 is now the best Angular 1 version out there and that you should update your applications to use it.

We continue to support Angular 1.2 with security patches as it is the last version of Angular to support Internet Explorer 8 and from now on Angular 1.5 will receive serious bug fixes and security patches.

Angular 1.6 will get regular non-breaking change releases over the next six months, and we will be aiming for the release of Angular 1.7 containing any necessary breaking changes by Summer 2017.

Thank you

As always the work on Angular 1 is a major collaborative effort between people both within and outside the Angular team. We hope that it continues to provide the solid application development platform that you have been relying on for over 7 years!

Angular 2.3.0 Now Available

Angular version 2.3.0 - is now available. This is a minor release following our announced adoption of Semantic Versioning, meaning that it contains no breaking changes and that it is be a drop-in replacement for 2.x.x. This is the final minor release for 2.x.

What's new?
  • We're now releasing the first version of the Angular Language Service. This is a service that is designed to integrate with IDEs and provide error checking and type completion within Angular Templates. We've built this service independent of editor, but we will soon be releasing an initial set of bindings for VS Code.
  • Developers can now take advantage of object inheritance for components. Share or simplify component functionality by inheriting from a parent component.
  • The latest release of zone.js includes improved stack traces. You should see stack traces that are shorter and are zone-aware:
    • 2.2.x Stack Trace:
      Error.spec.js:53 Error: Inside at ZoneAwareError (zone.js:652) at insideRun (Error.spec.js:31) at ZoneDelegate.invoke (zone.js:216) at (zone.js:100) at testFn (Error.spec.js:29) at ZoneDelegate.invoke (zone.js:216) at (zone.js:100) at Object.eval (Error.spec.js:19)
    • 2.3.0 Stack Trace:
      Error.spec.js:54 Error: Inside [InnerZone] at insideRun (Error.spec.js:31) [InnerZone] at (zone.js:100) [<root> => InnerZone] at testFn (Error.spec.js:29) [<root>] at (zone.js:100) [ProxyZone => <root>] at Object.eval (Error.spec.js:19) [ProxyZone]

For the complete list of features and bugfixes please see the changelog.

Monday, November 14, 2016

Angular 2.2.0 Now Available

Angular version 2.2.0 - is now available. This is a minor release following our announced adoption of Semantic Versioning, meaning that it contains no breaking changes and that it is be a drop-in replacement for 2.1.x.

What's new?
  • You can now AOT compile your Angular 2 Components and Modules when using @angular/upgrade. Check out the upgrade guide on our docs site.
  • We've added features to the router to assist with version 1.x to 2.x migrations.
  • Code generated from AOT compilation (NgFactories) will now be smaller in cases with large numbers of forms. We will continue to improve the size of generated code over time.
  • We've added guides on using Angular with ES5 and ES6/7.

For the complete list of features and bugfixes please see the changelog.