Muhi Masri

How to Create a Single File Component in Angular

A few easy steps to create a single file component with Angular including intellisense and auto-generation configuration.

Last updated on May 29, 2021

angular
architecture
Angular File

If you come from a Vue or React (styled component/JSS) background, a single file component is your “normal” definition of a component. I fully appreciate the separation of concern that Angular conveys to the world along with all the amazing features that it provides out of the box. But in some cases, especially when building a design system, components tend to be small and it might make more sense to encapsulate JS, HTML, and CSS in one single file representing a customized and composable UI element.

In this article, I will walk you through few easy steps you need to make a single file component with Angular including intellisense and auto-generation configuration.

Setup Angular Project

Install Angular CLI and create a new project

npm install -g @angular/cli
ng new angular-single-file-component

Add Angular Configuration

When running ng g component, Angular by default creates a folder with four files (ts, html, css, and spec). We need to add a new configuration to make it generate only ts and spec files.

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

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

Generate a test component

Let’s use CLI in the command-line to generate a single file component:

ng g component single-file

The following folder with two files will be created:

image

And the single-file.ts file will look like this:

image 1

Add Syntax Highlighting and Intellisense Support

If you are using VS Code, installing Angular Language Service extension will enable syntax highlighting and intellisense:

image 2

And finally, we can try binding attributes and properties with intellisense:

You can access the complete repository here. I hope you enjoyed learning from this article and if you have any questions, please leave a comment below.

Bye for now!

Recommended Reading

Learn how to validate table rows and input fields with Angular Material and HTML form validation

angular
angular material

Discussion

Master your front-end development techniques 🌟

Subscribe to stay up-to-date and receive quality front-end development articles straight to your inbox!

No spam, sales, or ads. Unsubscribe anytime you wish.

© 2022, Muhi Masri