Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

ng serve and CLI commands

While working you constantly use a few CLI commands: one runs the development server, another creates file skeletons. Generating files with a command is easier than by hand: the CLI writes the correct boilerplate and a test right away.

The development server

ng serve

The command builds the application and serves it at http://localhost:4200. While the server runs, it watches your files: after you save, the page in the browser reloads by itself. Stop the server with Ctrl+C.

Useful flags:

ng serve --open        # open the browser right away
ng serve --port 4300   # another port

TypeScript and template errors are printed in the terminal and shown over the page in the browser.

Generating files

The ng generate command (short: ng g) creates a skeleton of the kind you need. Let's create the first component — the to-do list:

ng generate component todo-list

The CLI creates the folder src/app/todo-list with four files:

src/app/todo-list/
├── todo-list.ts
├── todo-list.html
├── todo-list.css
└── todo-list.spec.ts

The component class is called TodoList, and its tag is app-todo-list. Before version 20 the files were named todo-list.component.ts, and the class was TodoListComponent.

What else ng generate can do

CommandWhat it creates
ng g component nameA component
ng g service nameA service
ng g pipe nameA pipe — a value transformer
ng g directive nameA directive
ng g guard nameA route guard
ng g interceptor nameAn HTTP request interceptor

The name may include a folder: ng g component blog/post-list creates the component in src/app/blog/post-list. The --skip-tests flag skips the test file, and --dry-run only shows which files would be created.

Other commands

CommandPurpose
ng buildBuild the application for deployment
ng testRun the tests
ng add packageInstall a library and configure it
ng updateUpdate Angular to a new version
ng versionShow Angular and Node.js versions

The --help flag shows help for any command, for example ng generate component --help.

Common mistake

You can create a component by hand, but then it is easy to get the selector name wrong or forget the stylesheet that styleUrl points to. The build then stops with a "could not find file" error. While you are learning, create files with ng generate.

Thanks for reading!

Donate to the site — we work hard for you.