Angular CLI 1.5.0 is out with some nice new features!

If you want to upgrade to 1.5.0 without pain (or to any other version, BTW), I have created a Github project to help: angular-cli-diff. Choose the version you’re currently using (1.2.1 for example), and the target version (1.5.0 for example), and it gives you a diff of all files created by the CLI: angular-cli-diff/compare/1.2.1…1.5.0. You have no excuse for staying behind anymore!

Let’s see what new features we have!

Support for Angular 5 and its new compiler

This is probably the biggest feature of this release! As Angular 5 ships with an improved compiler (check out our article about that if you missed it), the CLI can now use it (and will automatically if your project uses ng 5). It gives us faster builds, and even an AoT mode that starts to be usable in development (using the incremental rebuild).

For example, on a medium-sized application, where ng serve rebuilds in ~400ms, you can see the difference between the versions if you use AoT compilation:

  • ng serve --aot with ng 4.4 and CLI 1.4: ~4000-8000ms
  • ng serve --aot with ng 5.0 and CLI 1.5: ~1800-3600ms

As you may know, building with the AoT mode also compiles the templates, and thus detects errors at build time that you would only discover (hopefully) at runtime in JIT mode. Which is pretty useful, but used to be too slow to be usable in development. Now it starts to be more bearable, even if it’s still slower than JiT compilation, but the Angular team is working hard on this, and it starts to show (even if it is still too slow on big projects).

By default, the build-optimizer plugin (which does a little bit of extra work on your generated code, like removing unneeded decorators, adding hints for dead code removals, etc.) will now be applied to your build if you are using Angular 5 and building in AoT.

That means that your build command:

ng build --prod --build-optimizer

can be simplified to:

ng build --prod

once you have upgraded to the CLI 1.5 and Angular 5.

ES2015 as a target

The CLI now supports ES2015 as the target of the build (and not only ES5). If you are targeting only modern browsers, you can now choose to output ES2015 code as the result of your build. Just change the target of your tsconfig.json file and you’re set! (fun fact: it slimmed down the bundles generated when I tried it, but I can’t say it will always be the case…).

Auto loading of locale files for internationalization

Angular 5 introduced some breaking changes regarding internationalization: Angular stopped relying on the Intl API (that should be provided by the browser, but is not always, and polyfills can be buggy) and now requires you to load explicitly the locale data you need. For example the DatePipe needs to know the day names in french if you want to localize your app in this language. To do so, you need to have somewhere in your app:

import { registerLocaleData } from '@angular/common';
import localeFr from '@angular/common/locales/fr';

registerLocaleData(localeFr);

The problem is that if you build your application in 5 different languages, you need to do this for each language, and you don’t want to include every locale in every build 🤔.

This is the cool feature introduced by the CLI 1.5: you don’t have to do this yourself! The CLI will automatically add these lines of code, with the correct locale data, when you build your app (based on the locale you specified when you build):

ng build --aot --locale=fr

When you are building or serving the app in JiT mode, the CLI will do the same trick:

ng serve --locale=fr

But for your app to work without AoT, you’ll have to set the LOCALE_ID manually (whereas the CLI does it for you automatically in AoT mode). As the AoT mode will become the default soon (scheduled for CLI 2.0), this is not really bothering.

Resource integrity

The CLI now adds integrity and crossorigin attributes to scripts and stylesheets, that modern browsers use to check if the resource fetched has not been corrupted (by a “man in the middle” type of attack). You don’t have to do anything, and your application is safer!

TypeScript version mismatch

Angular CLI warns you if you are using a version of TypeScript which is not the recommended one with your Angular version (as it can lead to unnecessary headaches). You can now deactivate the warning for your project (if you are sure about what you are doing of course 😅) with ng set warnings.typescriptMismatch=false (it was previously only global).

appRoot configurable

The appRoot is now configurable in a CLI app, the default being app as it is right now. The main use of this feature is for people who want to have several apps in the same src directory, each with their own name.

Schematics template

The new schematics tool used by the CLI under the hood to generate … schematics (blueprints) of projects, is very generic and allows to create your own schematics. But how do you do that? To help with this question, the CLI team released a collection called @schematics/schematics containing a schematic for a schematic (so like a meta-schematic. That’s a lot of schematic, I know). This sample demonstrates a few common features and is a good starting point if you want to try to build your own project templates.

yarn global add @angular-devkit/schematics @schematics/schematics
schematics @schematics/schematics:schematic --name my-custom-schematics

Nx schematics

A new unofficial schematic has been released by nwrl.io. As I was saying in my last blog post, it didn’t took long for the community to start producing these! It’s called Nx and focuses on creating CLI projects containing several applications and components libraries in the same repository. If your company needs to have several applications using the same set of common components and services, you should check it out for inspiration: nrwl/nx. The schematic also uses ngrx and can generate examples with unit tests included.

Check out our ebook, online training (Pro Pack) and training if you want to learn more!


Cédric Exbrayat


Ninja Squad books


Become a ninja with Angular
Cover of ebook Become a ninja with Angular

Pay what you want and support charity!


Devenez un Ninja avec AngularJS
Couverture du livre Devenez un Ninja avec AngularJS

Passez de débutant à ninja en AngularJS 1.4 avec un ebook à prix libre et pour une bonne cause !


Ninja Squad books



Formations

Angular

11-13 dec. à Paris
26-28 fev. à Lyon
19-21 mar. à Paris

Angular avancé

14-15 dec. à Paris
22-23 mar. à Paris


Suivez-nous


Angular 5.0.0 is here!

Angular logo

We made a little video to give you an overview of the new features. If you want to dive deeper into what has changed, keep on reading after watching it ;).

Angular compiler is now much faster and more powerful!

As you may know, Angular has two ways to work:

  • one where the templates are compiled at runtime (Just in time, JiT)
  • one where the templates are compiled at build time (Ahead of time, AoT)

The second way is far better, as the work is done on the developer’s machine at build time, and not for each user at runtime, making the application start faster. It also allows compiling all the templates of the application and catch errors early. But this compiler was a bit slow before Angular 5.0, and as a result, most of us were using the JiT mode in development and the AoT mode only for production (that’s what Angular CLI does by default).

The main reason for this slowness was that every template change was triggering a full compilation of the application! That’s no longer the case: leveraging the new “pipeline transformer” ability of the TypeScript compiler (introduced in TS 2.3, as I was talking about in my previous article), the Angular compiler, ngc, is now able to only compile what is necessary with the introduction of a new watch mode:

ngc --watch

A new flag --diagnostics has also been introduced to print how much time the compiler spent on a compilation in watch mode.

We can expect the Angular CLI to use this new watch mode and it will probably become the default mode very soon!

The compiler can also check more thoroughly your templates, with the new option fullTemplateTypeCheck. It can for example catch that a pipe is not used with the proper type:

<!-- lowercase expects a string -->
<div>{{ 12.3 | lowercase }}</div>

This example will compile with ngc but not if fullTemplateTypeCheck is activated:

Argument of type '12.3' is not assignable to parameter of type 'string'

It can also analyze the local variables referencing a directive in your templates. For example, let’s say you created a variable to reference a ngModel, and want to access the hasError() method, but made a typo:

<input [(ngModel)]="user.password" required #loginCtrl="ngModel">
<!-- typo in `hasError()` method -->
<div *ngIf="loginCtrl.hasEror('required')">Password required</div>

This will also compile with ngc, except if fullTemplateTypeCheck is activated:

Property 'hasEror' does not exist on type 'NgModel'. Did you mean 'hasError'?

That’s super cool! Right now the default value of fullTemplateTypeCheck is false, but we can expect to see it become true in a future release. (Side note: this feature is currently a bit flaky, and I ran into issues testing it. You might want to wait 5.0.x to try it!).

The compiler is now also smarter to understand factories, and there’s thus no need to use this weird trick anymore:

export function webSocketFactory() {
  return WebSocket;
}

@NgModule({
  providers: [
    { provide: WEBSOCKET, useFactory: webSocketFactory },
  ]
})
export class AppModule {

You can now directly write:

@NgModule({
  providers: [
    { provide: WEBSOCKET, useFactory: () => WebSocket },
  ]
})
export class AppModule {

Forms

Forms have a tiny but really useful addition to their API: the ability to decide when the validity and value of a field or form is updated. This is something we already had in AngularJS 1.x, but not yet in Angular.

To do so, the FormControl allows to use an options object as the second parameter, to define the synchronous and asynchronous validators, and also the updateOn option. Its value can be:

  • change, it’s the default: the value and validity are updated on every change;
  • blur, the value and validity are then updated only when the field lose the focus;
  • submit, the value and validity are then updated only when the parent form is submitted.

So you can now do something like this:

this.passwordCtrl = new FormControl('', {
  validators: Validators.required,
  updateOn: 'blur'
});

It’s also possible to define this option on the FormGroup level, to have all the fields of the group behaving the same:

this.userForm = new FormGroup({
  username: '',
  password: ''
}, { updateOn: 'blur' });

This is of course also possible in template-driven form, with the ngModelOptions input of the NgModel directive:

<input [(ngModel)]="user.login" [ngModelOptions]="{ updateOn: 'blur' }">

or the new ngFormOptions input of the NgForm directive to apply on all fields:

<form [ngFormOptions]="{ updateOn: 'submit' }">

You can learn more about the plans for forms in this design docs.

Http

The old @angular/http module is now officially deprecated and replaced by @angular/common/http, the new HttpClient introduced in 4.3. You can probably expect that @angular/http will be removed in Angular 6.0.

HttpClient has been slightly improved with Angular 5.0, as we are now able to directly use object literals as headers or parameters, whereas we had to use the classes HttpHeaders and HttpParams.

So this kind of code:

const headers = new HttpHeaders().set('Authorization', 'secret');
const params = new HttpParams().set('page', '1');
return this.http.get('/api/users', { headers, params });

can now be simplified into:

const headers = { 'Authorization': 'secret' };
const params = { 'page': '1' };
return this.http.get('/api/users', { headers, params });

Animations

Two new transition aliases are introduced: :increment and :decrement. Let’s say you want to animate a carousel with 5 elements, with a nice animation based on the index of the element displayed. You had to declare a transition like: transition('0 => 1, 1 => 2, 2 => 3, 3 => 4', ...). With Angular 5, you can now use transition(':increment')!

Router

The router gains two new events to track the activation of individual routes:

  • ChildActivationStart
  • ChildActivationEnd

These events are introduced to give a more fine-grained control than using the global NavigationStart/NavigationEnd events, if you for example want to display a spinner while some children components are loading.

More newsworthy, it’s now possible to reload a page when the router receives a request to navigate to the same URL. Until now it was ignoring such a request, making it impossible to build a “refresh” button.

It’s now configurable at the router level, using onSameUrlNavigation, which can receive either reload or ignore (currently the default).

providers: [
  // ...
  RouterModule.forRoot(routes, {
    onSameUrlNavigation: 'reload'
  })
]

i18n

The messages extracted from your application now include the interpolations used in the template.

Before:

<source>
  Welcome to Ponyracer
  <x id="INTERPOLATION"/>
  <x id="INTERPOLATION_1"/>!
</source>

Now:

<source>
  Welcome to Ponyracer
  <x id="INTERPOLATION" equiv-text="{{ user.firstName }}"/>
  <x id="INTERPOLATION_1" equiv-text="{{ user.lastName }}"/>!
</source>

This can be really helpful for the translators, as they now have a hint about the interpolations.

A notable change in i18n is that the i18n comments are now deprecated. In Angular 4, you could use:

<!--i18n: @@home.justText -->
  I don't output an element, just text
<!--/i18n-->

Starting with Angular 5, you are encouraged to use an already possible alternative with ng-container:

<ng-container i18n="@@home.justText">
  I don't output an element, just text
</ng-container>

Pipes, i18n and breaking changes

More importantly, the pipes that were helping with the internationalization (number, percent, currency, date) have been completely overhauled. They don’t rely on the Intl API anymore. This internationalization API was supposed to be provided by the browser, but that was not always the case, so we had to use a polyfill, and inconsistencies between browsers (and polyfills) led to numerous bugs.

If you don’t do anything when you upgrade, you’ll use the new pipes by default. The good news is that there should be less bugs and you can remove the Intl polyfill you likely included. The bad news is that they don’t all have the same parameters and behavior as previously, and that can break your application.

Using a different locale than the default one (en-US) now requires to load additional locale data:

import { registerLocaleData } from '@angular/common';
import localeFr from '@angular/common/locales/fr';

registerLocaleData(localeFr);

All the i18n pipes now take a locale as their last parameter, allowing to dynamically override it:

@Component({
  selector: 'ns-locale',
  template: `
    <p>The locale is {{ locale }}</p>
    <!-- will display 'en-US' -->

    <p>{{ 1234.56 | number:'1.0-3':'fr-FR' }}</p>
    <!-- will display '1 234,56' -->        
  `
})
class DefaultLocaleComponentOverridden {
  constructor(@Inject(LOCALE_ID) public locale: string) { }
}

The currency pipe now takes a string as it second parameter, allowing to chose between 'symbol' (default), 'symbol-narrow' or 'code'. For example, with canadian dollars:

<p>{{ 10.6 | currency:'CAD' }}</p>
<!-- will display 'CA$10.60' -->

<p>{{ 10.6 | currency:'CAD':'symbol-narrow' }}</p>
<!-- will display '$10.60' -->

<p>{{ 10.6 | currency:'CAD':'code':'.3' }}</p>
<!-- will display 'CAD10.600' -->

The date pipe has several breaking changes. I won’t list them, it’s easier to check out the commit message.

All things are not lost if you want to keep the “old” pipes for now, as they have been kept in a new module DeprecatedI18NPipesModule, that you can import if you want to still use them:

@NgModule({
  imports: [CommonModule, DeprecatedI18NPipesModule],
  // ...
})
export class AppModule {

Service Workers

Angular has a package called @angular/service-worker, which has been in beta for quite some time and in a different repository. It received a little bit of love with Angular 5, as it graduated to the main repository, so we can expect it to be brought to the same quality standards as the other packages, and to be out of beta soon!

If you don’t know about service workers, you can picture them as small proxies in your browser. If you activate them in an app, it allows to cache static assets, and to not fetch them on every reload, improving performances. You can even go offline, and your app can still respond!

@angular/service-worker is a small package, but filled with cool features. Did you know that if you add it to your Angular CLI application, and turn a flag on ("serviceWorker": true in .angular-cli.json), the CLI will automatically generate all the necessary stuff to cache your static assets by default? And it will only download what has changed when you deploy a new version, allowing blazingly fast application start!

But it can even go further, allowing to cache external resources (like fonts, icons from a CDN…), route redirection and even dynamic content caching (like calls to your API), with different strategies possible (always fetch for fresh data, or always serve from cache for speed…). The package also offers a module called ServiceWorkerModule that you can use in your application to react to push events and notifications!

Other breaking changes

A few things that were deprecated in Angular 4.0 have now been definitely removed.

There is a last breaking change that should not really impact you. I feel morally obligated to show it to you, but it’s totally not interesting.

If you are declaring extra providers in the platformXXXX() or bootstrapModule() methods, you now need to use the (new) StaticProvider, which is really similar to a Provider, but forces you to explicitly declare the dependencies. It does not impact the providers you declare in your modules and components, don’t worry.

So if you have something like this:

platformBrowserDynamic([
  MyCustomProviderA,
  MyCustomProviderB // depends on MyCustomProviderA
]).bootstrapModule(AppModule);

It must now be in 5.0:

platformBrowserDynamic([
  { provide: MyCustomProviderA, deps: [] },
  { provide: MyCustomProviderB, deps: [MyCustomProviderA] }
]).bootstrapModule(AppModule);

I honestly couldn’t come up with a decent real use-case, as it is quite rare to give extra providers to these methods, and this only impact the two cases in the example and not useValue, useFactory, useExisting… So I don’t think many apps will be impacted :)

On the other hand, this change allows Angular to not depend on the Reflect API, and that gives us (slightly) smaller bundles \o/.

Another change is the removal of the ES5 API to write Angular applications without decorators. This API was also depending on Reflect and is now gone.

All our materials (ebook, online training (Pro Pack) and training) are up-to-date with these changes if you want to learn more!


Cédric Exbrayat


Ninja Squad books


Become a ninja with Angular
Cover of ebook Become a ninja with Angular

Pay what you want and support charity!


Devenez un Ninja avec AngularJS
Couverture du livre Devenez un Ninja avec AngularJS

Passez de débutant à ninja en AngularJS 1.4 avec un ebook à prix libre et pour une bonne cause !


Ninja Squad books



Formations

Angular

11-13 dec. à Paris
26-28 fev. à Lyon
19-21 mar. à Paris

Angular avancé

14-15 dec. à Paris
22-23 mar. à Paris


Suivez-nous


Nous vous avions promis, dans notre article faisant le bilan des 5 ans de Ninja Squad de vous fournir le bilan comptable de ce dernier exercice quand il serait disponible. Et comme nous sommes transparents, super cools, et fiables (et humbles), nous tenons promesse.

Donc voici, pour les passionnés de chiffres, les curieux, ou les futurs entrepreneurs angoissés, notre bilan officiel 2016-2017 :

(le gendre idéal apparaissant sur la page de garde n’est ni un ninja, ni notre comptable… 🤷‍)


Cyril Lacôte


Ninja Squad books


Become a ninja with Angular
Cover of ebook Become a ninja with Angular

Pay what you want and support charity!


Devenez un Ninja avec AngularJS
Couverture du livre Devenez un Ninja avec AngularJS

Passez de débutant à ninja en AngularJS 1.4 avec un ebook à prix libre et pour une bonne cause !


Ninja Squad books



Formations

Angular

11-13 dec. à Paris
26-28 fev. à Lyon
19-21 mar. à Paris

Angular avancé

14-15 dec. à Paris
22-23 mar. à Paris


Suivez-nous


Angular 4.4.1 is here (4.4.0 glitched out and was never released)!

Angular logo

This is a fairly small release, with some bugfixes but not a lot of features. Angular 5.0, scheduled for next month, will bring more awesomeness but we’ll have to wait a little.

Let’s see what 4.4 has in stock for us!

Performance with preserveWhitespaces

A few things changed internally to boost performance, and a new compiler flag appeared that allows to remove extra whitespaces. This can look minor, but it can improve the generated code size, and also speed the components creation. But it can also break your layout if you rely on several consecutive spaces in your templates :) That’s why the default for the preserveWhitespaces flag is true for now, and might become false one day. But right now, you have to activate it manually.

You can configure it globally:

platformBrowserDynamic().bootstrapModule(AppModule, {
  preserveWhitespaces: false
});

or per component:

@Component({
  selector: 'pr-home',
  templateUrl: './home.component.html',
  preserveWhitespaces: false
})
export class HomeComponent implements OnInit, OnDestroy {

If you really want a whitespace to be kept, you can use a special entity called &ngsp;. It looks like &nbsp; with a typo, but it is not: it is a special character that the Angular compiler will transform in a whitespace. Note that it will only keep one whitespace, even if add several consecutive ones, like &ngsp;&ngsp;. If you really want to preserve the whitespaces in a fragment of a template, you can use ngPreserveWhitespaces:

<div ngPreserveWhitespaces>hello     there</div>

Note that the gains were fairly small on our applications, but a gain is a gain…

Multiple exportAs names

It’s not really important, but it’s the second and last feature of this release: you can now specify several names in the exportAs attribute of a directive. This is mostly introduced for allowing to change the name of existing directives, while still keeping the old one for backward compatibility.

For example:

@Directive({
  selector: '[ns-ninja]',
  exportAs: 'ninja, superNinja'
})
export class NinjaDirective {

can be used as:

<div ns-ninja #foo="ninja">
<!-- or -->
<div ns-ninja #foo="superNinja">

Summary

That’s all for this release: the next important one will be 5.0!

The Angular CLI also had interesting changes lately. Check out our blog posts if you missed them:

All our materials (ebook, online training (Pro Pack) and training) are up-to-date with these changes if you want to learn more!


Cédric Exbrayat


Ninja Squad books


Become a ninja with Angular
Cover of ebook Become a ninja with Angular

Pay what you want and support charity!


Devenez un Ninja avec AngularJS
Couverture du livre Devenez un Ninja avec AngularJS

Passez de débutant à ninja en AngularJS 1.4 avec un ebook à prix libre et pour une bonne cause !


Ninja Squad books



Formations

Angular

11-13 dec. à Paris
26-28 fev. à Lyon
19-21 mar. à Paris

Angular avancé

14-15 dec. à Paris
22-23 mar. à Paris


Suivez-nous


Angular CLI 1.4.0 is out with some nice new features!

If you want to upgrade to 1.4.0 without pain (or to any other version, BTW), I have created a Github project to help: angular-cli-diff. Choose the version you’re currently using (1.2.1 for example), and the target version (1.4.0 for example), and it gives you a diff of all files created by the CLI: angular-cli-diff/compare/1.2.1…1.4.0. You have no excuse for staying behind anymore!

Let’s see what new features we have!

Schematics

The Google team has created schematics, a Yeoman-like generator. Angular CLI will now use this new tool to generate the application skeleton and the components, services, pipes… All the blueprints are now bundled in schematics/@angular and have been removed from the CLI itself.

Really interesting as it opens the possibility to have other blueprints than the official ones! This is a feature that other frameworks also have (like Vue CLI or Ember CLI).

We can expect to see new “schematics” for Angular CLI really soon, for example some oriented for server-side rendering apps, or mobile apps, or progressive apps, or native apps, etc.

The CLI now has an option to specify the blueprint you want to use when you generate a project:

ng new --collection my-custom-schematics project-name

You can of course define your own schematics, but we did not give it a try yet.

Serve path

A new option for ng serve is available to specify a path where you want the application to be served in dev:

ng serve --serve-path hello

will serve the application at http://localhost:4200/hello. This is a simple way to configure it, even if you could do the same with the --base-href and --deploy-url flags.

Missing translation strategy

If you are using the i18n support of Angular, you can specify directly from the CLI the strategy you want to adopt when a translation is missing:

ng build --aot --locale fr --i18n-file src/i18n/messages.fr.xlf --missing-translation error

The --missing-translation error flag is available for the serve and build commands, and accepts the values error, warning or ignore.

Scripts sourcemaps and minifications

The scripts that were added via the scripts array in .angular-cli.json were not minified and had no sourcemaps. This is now resolved.

Check out our ebook, online training (Pro Pack) and training if you want to learn more!


Cédric Exbrayat


Ninja Squad books


Become a ninja with Angular
Cover of ebook Become a ninja with Angular

Pay what you want and support charity!


Devenez un Ninja avec AngularJS
Couverture du livre Devenez un Ninja avec AngularJS

Passez de débutant à ninja en AngularJS 1.4 avec un ebook à prix libre et pour une bonne cause !


Ninja Squad books



Formations

Angular

11-13 dec. à Paris
26-28 fev. à Lyon
19-21 mar. à Paris

Angular avancé

14-15 dec. à Paris
22-23 mar. à Paris


Suivez-nous


Angular a presque un an, et est bientôt en version 5.0 !

Le premier commit date de 3 ans, et nous avons commencé à l’utiliser dès le tout début. Nous avons enseigné les fondamentaux d’Angular à des centaines de développeurs en personne, notre ebook à des milliers de lecteurs, et notre formation en ligne (Pack Pro) a touché quelques centaines de développeurs supplémentaires tout autour du monde !

Tout au long de ce chemin, nous avons appris pas mal de choses sur Angular, son fonctionnement, son éco-système et comment construire de meilleures applications.

C’est pour cela que nous sommes très contents d’annoncer notre nouvelle formation sur 2 jours : Angular avancé: de Ninja à Héros !

Cette formation va au-delà des fondamentaux et se destine à des développeurs qui cherchent des sujets plus avancés et des bonnes pratiques.

Pour vous donner un aperçu, la formation couvre :

  • l’injection de dépendances : injecteur hiérarchique, pourquoi @Injectable, singleton vs plusieurs instances, comment partager des données dans votre application, les différents types de providers et leur utilité, @Optional, @Self, forwardRef ;
  • les observables : les opérateurs avancés et leur utilité, bonnes pratiques, comment les tester ;
  • les composants et directives avancés : méthodes du cycle de vie, ng-content, @HostBinging, @HostListener, ViewChild, ContentChild ;
  • les tests : tester les composants, comment tirer profit de l’injection de dépendances, tests asynchrones ;
  • le router : découper votre application en modules, lazy-loading, les pièges à éviter avec l’injection de dépendances, comment utiliser les guards et resolvers ;
  • le fonctionnement d’Angular : comment le framework fonctionne sous le capot, la détection de changement, les zones, la compilation JiT and AoT ;
  • les performances : les stratégies de détection de changement, tracking des éléments, le pipe async et ses pièges, comment échapper à la détection de changement d’Angular ;
  • l’internationalisation : qu’est-ce que l’i18n, comment construire une application multi-langues, bonnes pratiques ;
  • les formulaires : formulaires imbriqués, formulaires dynamiques, construire vos propres composants de formulaire avec ControlValueAccessor ;
  • et plein d’astuces sur la mise en production, comment faire de l’intégration continue, etc.

Cette formation s’appuie également sur notre Pack Pro que vous pouvez acheter avec notre ebook. Nous ferons quelques-uns des exercices les plus avancés ensemble pour que vous puissiez mettre en pratique ces nouveaux concepts !

Ho, et, comme toujours, la formation est 30% moins chère si vous êtes un développeur indépendant, un contributeur open-source, un organisateur de conférence ou si vous cherchez actuellement un emploi. Pour plus de détails, regardez notre site !


Cédric Exbrayat


Ninja Squad books


Become a ninja with Angular
Cover of ebook Become a ninja with Angular

Pay what you want and support charity!


Devenez un Ninja avec AngularJS
Couverture du livre Devenez un Ninja avec AngularJS

Passez de débutant à ninja en AngularJS 1.4 avec un ebook à prix libre et pour une bonne cause !


Ninja Squad books



Formations

Angular

11-13 dec. à Paris
26-28 fev. à Lyon
19-21 mar. à Paris

Angular avancé

14-15 dec. à Paris
22-23 mar. à Paris


Suivez-nous


Angular is nearly one year old, and soon in version 5.0!

The first commit is now 3 years old, and we’ve been using it since the very beginning. We have taught the fundamentals of Angular to hundreds of developers in person, our ebook has thousands of readers, and our online training (Pro Pack) reached a few hundred more developers all over the world!

Along the way we have learnt quite a bit about Angular, its internals, its ecosystem and how to build better applications.

That’s why we are really happy to announce our new 2 days training: Advanced Angular: from Ninja to Hero!

This training goes beyond the fundamentals and is built for developers who are looking for more advanced topics and best practices.

To give you an overview, the training deep dives in:

  • dependency injection: hierarchical injector, why @Injectable, singleton vs several instances, how to share data in your application, the different types of providers and their use, @Optional, @Self, forwardRef;
  • observables: advanced operators and use-cases, best practices, how to test them;
  • advanced components and directives: lifecycle hooks, ng-content, @HostBinging, @HostListener, ViewChild, ContentChild;
  • testing: component tests, how to leverage dependency injection, asynchronous tests;
  • router: how to split your application in modules, lazy-loading, the traps to avoid with dependency injection, how to use guards and resolvers;
  • Angular internals: how does it work under the hood, change detection, zones, JiT and AoT compilation;
  • performance: change detection strategies, element tracking, the async pipe and its traps, how to escape Angular’s change detection;
  • internationalization: what’s i18n, how to build a multi-language application, best practices;
  • forms: nested forms, dynamic forms, build your own form component with ControlValueAccessor;
  • and a lot of tips on how to be ready for production, how to set up a continuous integration, etc.

This training also relies on our online training, the Pro Pack that you can buy with our ebook. We’ll go over some of the more advanced exercises of the “Pro Pack” so you can get your hands dirty with all these new concepts!

Oh, and, as always, the training is 30% cheaper if you are an independent developer, an open source committer, a conference organizer or if you are currently looking for a job. If you want to have more details, check out our website!


Cédric Exbrayat


Ninja Squad books


Become a ninja with Angular
Cover of ebook Become a ninja with Angular

Pay what you want and support charity!


Devenez un Ninja avec AngularJS
Couverture du livre Devenez un Ninja avec AngularJS

Passez de débutant à ninja en AngularJS 1.4 avec un ebook à prix libre et pour une bonne cause !


Ninja Squad books



Formations

Angular

11-13 dec. à Paris
26-28 fev. à Lyon
19-21 mar. à Paris

Angular avancé

14-15 dec. à Paris
22-23 mar. à Paris


Suivez-nous


Angular CLI 1.3.0 is out with some nice new features!

It now officially supports ES2017 and TypeScript 2.4 and is ready for Angular 5 (which should be out shortly).

You can check out what files you need to update using angular-cli-diff, for example if you are currently using 1.2.1: angular-cli-diff/compare/1.2.1…1.3.0

Let’s see what new features we have!

Bundle sizes

The Angular team is putting a ton of work to generate the smallest bundles possible. Angular CLI uses Webpack 3 and now leverages its scope hoisting feature which resulted in some nice gains, but there is still room for improvements.

The Angular team is working on a better tree-shaking with a new project @angular/devkit, that the CLI now uses. It’s a bit experimental, so it’s behind a new flag called --build-optimizer. It does some manipulations on your compiled code, like folding the static properties inside the class, scrubbing the Angular specific decorators and metadata (that are unneeded when you have compiled in AoT mode), adding a /*@__PURE__*/ comment on classes, etc. All these actions aim for the same goal: helping Webpack and Uglify to do a better tree-shaking and a better dead code elimination.

And all that gives us smaller bundles \o/ I tested it on a medium-size application:

Size without --build-optimizer: 871K (211K gzip)

With --build-optimizer: 778K (192K gzip)

That’s a small but nice win. But for others it resulted in massive gains! So it can be interested for you, especially if you are using Angular Material (check the comments of this issue).

You can read more about how this feature works here. Be warned that it is experimental though, and can break your app, so be careful…

Named chunks

While we are talking about building the application, a new flag, called --named-chunks, will generate nicely named chunks. Until now, if you had lazy-loaded modules in your application, the bundles looked like that:

main.bundle.js
0.chunk.js
1.chunk.js

With this new flag, the CLI names it with the names of the Angular modules:

main.bundle.js
users.module.chunk.js
admin.module.chunk.js

This is the default in development mode so you don’t even have to add the flag to your command, but it’s not the default in production mode.

Server side rendering

The SSR is getting better and better, and the CLI now has a piece of documentation to guide you, check it out: universal rendering. It’s honestly still very early days, and won’t work with most apps (no lazy-loading support for example).

Proxy configuration

It’s possible to define a proxy configuration since some time now, and it’s quite useful as you can for example forward all the requests to an API to a local server running on your machine (really useful when you are developing the backend too).

{
  "/api": {
    "target": "http://localhost:9000",
    "secure": false
  }
}

But you had to manually give it to the serve command every time, like ng serve --proxy-config proxy.conf.json, which was a bit painful.

You can now specify a proxyConfig in your .angular-cli.json file, and ng serve will pick it up automatically.

Check out our ebook, online training (Pro Pack) and training if you want to learn more!


Cédric Exbrayat


Ninja Squad books


Become a ninja with Angular
Cover of ebook Become a ninja with Angular

Pay what you want and support charity!


Devenez un Ninja avec AngularJS
Couverture du livre Devenez un Ninja avec AngularJS

Passez de débutant à ninja en AngularJS 1.4 avec un ebook à prix libre et pour une bonne cause !


Ninja Squad books



Formations

Angular

11-13 dec. à Paris
26-28 fev. à Lyon
19-21 mar. à Paris

Angular avancé

14-15 dec. à Paris
22-23 mar. à Paris


Suivez-nous


Angular 4.3.0 is here!

Angular logo

This is a fairly big release, with a new HttpClientModule, a complete rewrite of the HttpModule 💅! This should be the last minor release before Angular 5, when we can expect some other exciting stuff!

HttpClientModule

The biggest feature of this release is without a doubt the new HttpClientModule. This module is a complete rewrite of the current HttpModule that had some defaults, like the obligation to extract the JSON from the response for every request, no mechanism to handle requests and responses in a generic fashion, and a quite awful testing API.

The new HttpClientModule is a really cool alternative: it solves all these issues, and we migrated our applications fairly easily. And it was mostly code deletions 💖.

We made a little video to show you the difference, and a complete article to help you to migrate your applications.

It showcases the brand new HttpClient service, how to write unit tests, and how to use the new interceptors!

Check out the article we wrote that explains in deep how to use this new module!

Router

A few events have been added to the router, if you need to know when a resolver or a guard is run:

  • ResolveStart, ResolveEnd
  • GuardsCheckStart, GuardsCheckEnd

Forms

The two new validators min and max released with 4.2 have been temporarily rolled back as they were breaking changes :(. They’ll return in a major release, probably 5.0.0.

Style

You may know that the /deep/ “shadow-piercing” combinator can be used to force a style down to child components. This selector had an alias >>> and now has another one called ::ng-deep.

Be warned though: the /deep/ combinator has been deprecated from the Shadow DOM spec and is being removed from all major browsers. So the support will probably also be dropped by Angular in the future. Until then, it is recommended to use ::ng-deep, and to only use it with emulated view encapsulation.

Compiler

This is not really a new feature, but I think it is interesting to understand how things work under the hood.

TypeScript 2.3 recently introduced the concept of transformers in the compiler API. That means some teams can write custom transformations/plugins that are applied to the code compiled by tsc. This is not really something that we common mortals will write, but Angular has its own compiler called ngc that wraps tsc.

Until now, the process for ngc was to compile your templates to generate TypeScript files, and then call tsc to compile your TypeScript code and the TypeScript files generated to JavaScript. If that sounds strange, you can check out our ebook where we explain all this.

With the introduction of transformers, tsc works slightly differently: it starts by parsing the files, does the type-checking, applies any plugin you want, and then generates JavaScript.

Based on this, ngc is now becoming a plugin called in the TypeScript compilation pipeline, rather than a wrapper of the TypeScript compiler.

As Angular developers, we can expect to have very precise type-checking in our templates, referring to the exact line of the problem in HTML source file!

Summary

That’s all for this release: the next important one will be 5.0!

In the meantime, all our materials (ebook, online training (Pro Pack) and training) are up-to-date with these changes if you want to learn more!


Cédric Exbrayat


Ninja Squad books


Become a ninja with Angular
Cover of ebook Become a ninja with Angular

Pay what you want and support charity!


Devenez un Ninja avec AngularJS
Couverture du livre Devenez un Ninja avec AngularJS

Passez de débutant à ninja en AngularJS 1.4 avec un ebook à prix libre et pour une bonne cause !


Ninja Squad books



Formations

Angular

11-13 dec. à Paris
26-28 fev. à Lyon
19-21 mar. à Paris

Angular avancé

14-15 dec. à Paris
22-23 mar. à Paris


Suivez-nous


Angular 4.3 introduced a new module, HttpClientModule, which is a complete rewrite of the existing HttpModule.

This article will show you how to easily migrate to this new module, and why you should (spoiler: because it’s way better 🦄).

Here is a short video we made to show you what’s new with this HttpClientModule.

The rest of the article focuses on what you have to do to migrate your apps. It assumes an app generated with Angular CLI, but if that’s not your case, you’ll still be able to follow, minus some file names that might differ for you.

Migrate your application

The first step is to remove the @angular/http package from your package.json file. Indeed the new HttpClientModule is in the @angular/common/http package, and @angular/common should already be in your package.json file.

Save your file, and run NPM or Yarn to update the node_modules. You should start to see compilation errors in your application, as all the imports from @angular/http are now breaking. That’s good, because it tells you all the files you’ll have to migrate.

The first obvious one is your app.module.ts file, which contains your main NgModule. Replace HttpModule with HttpClientModule in your module’s imports field, and update the TypeScript import from:

import { HttpModule } from '@angular/http';

to:

import { HttpClientModule } from '@angular/common/http';

The second step is to replace every instance of the service Http with the new service HttpClient. This is will usually be the case in your services. This is where using the new HttpClient will shine: you don’t have to manually extract the JSON anymore \o/!

So a service which was looking like that:

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import { UserModel } from './user.model';

@Injectable()
export class UserService {

  constructor(private http: Http) {}

  list(): Observable<UserModel> {
    return this.http.get('/api/users')
      .map(response => response.json())
  }
}

can be rewritten as:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import { UserModel } from './user.model';

@Injectable()
export class UserService {

  constructor(private http: HttpClient) {}

  list(): Observable<UserModel> {
    return this.http.get('/api/users');
  }
}

Feels good to remove this code, doesn’t it?

Migrate your tests

Now let’s move on to the unit tests.

Testing services with HTTP requests was really verbose with HttpModule… You probably had something like:

describe('UserService', () => {

  beforeEach(() => TestBed.configureTestingModule({
    imports: [HttpModule],
    providers: [
      MockBackend,
      BaseRequestOptions,
      {
        provide: Http,
        useFactory: (backend, defaultOptions) => new Http(backend, defaultOptions),
        deps: [MockBackend, BaseRequestOptions]
      },
      UserService
    ]
  }));

  it('should list the users', async(() => {
    const userService = TestBed.get(UserService);
    const mockBackend = TestBed.get(MockBackend);
    // fake response
    const expectedUsers = [{ name: 'Cédric' }];
    const response = new Response(new ResponseOptions({ body: expectedUsers }));
    // return the response if we have a connection to the MockBackend
    mockBackend.connections.subscribe((connection: MockConnection) => {
      expect(connection.request.url).toBe('/api/users');
      expect(connection.request.method).toBe(RequestMethod.Get);
      connection.mockRespond(response);
    });

    userService.list().subscribe((users: Array<UserModel>) => {
      expect(users).toEqual(expectedUsers);
    });
  }));
});

You can now use the new testing API, which is much, much nicer:

describe('UserService', () => {

  beforeEach(() => TestBed.configureTestingModule({
    imports: [HttpClientTestingModule],
    providers: [UserService]
  }));

  it('should list the users', () => {
    const userService = TestBed.get(UserService);
    const http = TestBed.get(HttpTestingController);
    // fake response
    const expectedUsers = [{ name: 'Cédric' }];

    let actualUsers = [];
    userService.list().subscribe((users: Array<UserModel>) => {
      actualUsers = users;
    });

    http.expectOne('/api/users').flush(expectedUsers);

    expect(actualUsers).toEqual(expectedUsers);
  });
});

That should remove a lot of errors you have or all of them.

Maybe you were also adding headers or params to your requests. The new HttpClient allows it too:

const params = new HttpParams().set('page', '1');
this.http.get('/api/users', { params });

const headers = new HttpHeaders().set('Authorization', `Bearer ${token}`);
this.http.get('/api/users', { headers });

In the example above, I set the JWT token needed in the Authorization header. This is something you probably repeat a lot of times in your services, as every request needs it.

The new module introduces a very interesting feature: interceptors. These interceptors are called for every request and response, and allow to easily handle tasks like adding a header to every request, or handling errors in a generic way for example.

First create your interceptor:

@Injectable()
export class GithubAPIInterceptor implements HttpInterceptor {

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(req);
  }

}

Then add your custom logic, for example to add an OAUTH token to every Github API request, but not to the other requests:

@Injectable()
export class GithubAPIInterceptor implements HttpInterceptor {

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    // if it is a Github API request
    if (req.url.includes('api.github.com')) {
      // we need to add an OAUTH token as a header to access the Github API
      const clone = req.clone({ setHeaders: { 'Authorization': `token ${OAUTH_TOKEN}` } });
      return next.handle(clone);
    }
    // if it's not a Github API request, we just handle it to the next handler
    return next.handle(req);
  }

}

If you want to learn more about this API and Angular in general, you can check out our ebook, online training (Pro Pack) and training!


Cédric Exbrayat


Ninja Squad books


Become a ninja with Angular
Cover of ebook Become a ninja with Angular

Pay what you want and support charity!


Devenez un Ninja avec AngularJS
Couverture du livre Devenez un Ninja avec AngularJS

Passez de débutant à ninja en AngularJS 1.4 avec un ebook à prix libre et pour une bonne cause !


Ninja Squad books



Formations

Angular

11-13 dec. à Paris
26-28 fev. à Lyon
19-21 mar. à Paris

Angular avancé

14-15 dec. à Paris
22-23 mar. à Paris


Suivez-nous


Posts plus anciens