0

A part of my Schematics needs to install Angular Material. However, Angular Material is usually installed via the command:

ng add @angular/material

How do I make my Schematics to run the command ng add @angular/material? I would expect it run that command, and the regular process of installing Angular Material will happen (asking for theme, typography, etc.).

The only resource is this.

Following along, I have made my script as follow, but it didn't seem to run the command at all:

function ngAddAngularMaterial() {
    return (host: Tree, context: SchematicContext) => {
        const workspace = getWorkspace(host);
        const projectName = Object.keys(workspace.projects)[0];
        const project = workspace.projects[projectName];
        const projectPath = join(normalize(project.root), 'src');
        const possibleFiles = ['/angular.json', '/.angular.json'];
        const angularJSONPath = possibleFiles.filter((path) => host.exists(path))[0];

        if (project.projectType !== 'application') {
            context.logger.error('❌ Cannot add @angular/material in a non-application Angular project.');
        } else {
            if (!project.architect) {
                throw new SchematicsException(
                    `Cannot read the output path (architect.build.options.outputPath) of the Angular project "${projectPath}" in angular.json`
                );
            }

            project.architect['deploy'] = {
                builder: '@angular/material:add',
                options: {},
            };
            host.overwrite(angularJSONPath, JSON.stringify(workspace, null, 4));
            context.logger.info(`✔️  Rewrote "${angularJSONPath}"`);
        }

        return host;
    };
}

It still prints out:

✔️ Rewrote "/angular.json"

But ng add @angular/material was not actually installed.

timthekoder
  • 415
  • 5
  • 16

1 Answers1

1

This is a quite old question but here is my take on this. If you want to launch another schematics, you need to call externalSchematics.

This is an example with Transloco :

 /**
 * Force langs to fr,en
 * @param project : ng project that schematics run on
 */
function addTransloco(project: string): Rule {
  return (tree: Tree, context: SchematicContext) => {
    context.logger.debug("Adding transloco files");
    return chain([
      externalSchematic('@ngneat/transloco', 'ng-add', {
        project: project,
        langs: 'fr,en',
        ssr: false
      })
    ])(
      tree,
      context
    );
  };
}

Note that you need to declare the external library in your schematics package, like that :

  "dependencies": {
    "@angular-devkit/core": "10.2.3",
    "@angular-devkit/schematics": "10.2.3",
    "@fortawesome/angular-fontawesome": "0.8.0",
    "@ngneat/transloco": "2.21.0",
Alain Boudard
  • 768
  • 6
  • 16