Home > other >  How can I generate a single-file component with Angular's CLI?
How can I generate a single-file component with Angular's CLI?

Time:01-27

Let's suppose I need an Angular component which is so small that the best option for it would be a single-file component.

An error alert like the one below would be such an example:

@Component({
  selector: 'app-errors',
  template: `<div >{{ errorMessage }}</div>`,
  styles: [
    `
    .alert-error {
      color: #721c24;
      background-color: #f8d7da;
      border-color: #f5c6cb;
      padding: 0.75rem 1.25rem;
      margin-bottom: 1rem;
      text-align: center;
      border: 1px solid transparent;
      border-radius: 0.25rem;
    }
    `,
  ],
})
export class ErrorsComponent {}

In order to make this component I have run ng g c error-alert in the CLI. Then I deleted all the files generated by the CLI except error-alert.ts. Then I moved it outside of the error-alert directory (which I deleted).

The problem

I wished (and still do) there was a simpler and faster way to make a single-file component.

Questions

  1. Is there a CLI command that would generate a single-file component?
  2. If there isn't such a command, can we configure the CLI so that there is? How?

CodePudding user response:

You could try adding some flags like so.

> ng generate component <component-name> --inlineTemplate=true --inlineStyle=true --skip-tests=true

This should stop the generation of css/html/spec file.

There is now also an option on more modern versions to do the same with standalone components.

--standalone

More options surrounding generating with specific goals can be found in the angular CLI docs.

You can also edit schematics object in your angular.json to set these flags to default when generating a component if you wanted to take this further.

  "schematics": {
    "@schematics/angular": {
      "component": {
        "inlineTemplate": true
      }
    }
  }
  • Related