Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 class="alert-error">{{ 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?
like image 661
Razvan Zamfir Avatar asked Sep 06 '25 03:09

Razvan Zamfir


2 Answers

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
      }
    }
  }
like image 197
Dince12 Avatar answered Sep 10 '25 14:09

Dince12


You can add a new configuration to make ng g component generate only one ts and spec file.

In angular.json, add the following under "sematics" property:

"schematics": {
  "@schematics/angular:component": {
    "inlineStyle": true,
    "inlineTemplate": true
   }
}

Also, you can use extensions to get CSS and HTML syntax highlighting. Here is one - https://marketplace.visualstudio.com/items?itemName=Angular.ng-template

More in depth tutorial to creating single file component in Angular - https://muhimasri.com/blogs/how-to-create-a-single-file-component-in-angular/

like image 20
Muhi Avatar answered Sep 10 '25 15:09

Muhi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!