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 serveThe 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 portTypeScript 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-listThe 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.tsThe 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
| Command | What it creates |
|---|---|
ng g component name | A component |
ng g service name | A service |
ng g pipe name | A pipe — a value transformer |
ng g directive name | A directive |
ng g guard name | A route guard |
ng g interceptor name | An 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
| Command | Purpose |
|---|---|
ng build | Build the application for deployment |
ng test | Run the tests |
ng add package | Install a library and configure it |
ng update | Update Angular to a new version |
ng version | Show 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.