Sharing Top Content from the Angular-sphere.

Generating Custom Code with the Angular CLI and Schematics

Blogged: Generating Custom Code with the Angular CLI and Schematics

  • In our case, the component is quite simple: – – In addition to that, the template for this component is just a bunch of html tags with the right Bootstrap based classes — something I cannot learn by heart what’s the reason a generator seems to be a good idea:…
  • After executing this command we get an npm package with a collection that holds three demo schematics: – – The file contains metadata about the collection and points to the schematics in the three sub folders.
  • This file describes a property for each possible argument: – – The argument holds the name of the menu component, its as well as the path of the app ( ) and the folder ( ).
  • This function describes the necessary steps with a rule which normally makes use of further rules: – – For this factory, I’ve defined two helper constructs at the top of the file: – – The first one is the object which just groups some functions we will need later within…
  • After this, we can use the CLI to scaffold our side menu: – – Here, is the name of the schematic, the file name we are passing and the name of the npm package.

Angular Schulungen, Workshops und Beratung in Deutschland, Österreich und der Schweiz

Since some versions, the Angular CLI uses a library called Schematics to scaffold building blocks like components or services. One of the best things about this is that Schematics allows to create own code generators too. Using this extension mechanism, we can modify the way the CLI generates code. But we can also provide custom collections with code generators and publish them as npm packages. A good example for this is Nrwl’s Nx which allows to generated boilerplate code for Ngrx or upgrading an existing application from AngularJS 1.x to Angular.

These code generators are called Schematics and can not only create new files but also modify existing ones. For instance, the CLI uses the latter to register generated components with existing modules.

In this post, I’m showing how to create a collection with a custom Schematic from scratch and how to use it with an Angular project. The sources can be found here.

In addition to this, you’ll find a nice video with Mike Brocchi from the CLI-Team explaining the basics and ideas behind Schematics here.

To demonstrate how to write a simple Schematic from scratch, I will build a code generator for a Bootstrap based side menu. With an respective template like the free ones at Creative Tim the result could look like this:

Before creating a generator it is a good idea…

Generating Custom Code with the Angular CLI and Schematics

Comments are closed, but trackbacks and pingbacks are open.