Learning Angular: Creating Components
I am continuing my Angular learning journey by understanding how to
create components. First, creating component by hand and using the
Angular CLI tool: ng
to create component automatically.
An understanding of how to create components by hand will give an appreciation of what the Angular CLI tool does for you automatically.
The article will take less than three minutes to read.
Introduction
The last article covered specific parts of an Angular component file and how they connect to template and styles.
How to create a component for Angular to use?
- manually
- Angular tool: Angular CLI
Manual Component Creation
The minimum requirement to create an Angular component manually is to
create the *.component.ts
file, like
hello-world-manual.component.ts
. This is what it would look like:
I covered the anatomy of this file in this article. Using inline
values for the template
and the styles
allow for a single file
definition for a component.
Put this file, hello-world-manual.component.ts
, into a folder, say:
src/app/hello-world-manual/
.
Angular CLI
Angular’s tooling system, Angular CLI, can create components for you by running the command:
(Short-hands: g
and c
can replace generate
and component
,
respectively.)
The Angular CLI tool creates additional files:
- the styles file:
hello-world.component.css
- the template file:
hello-world.component.html
- the test file:
hello-world.component.spec.ts
- the component file:
hello-world.component.ts
If you want to create a smaller or similar file to the one created by hand, use options:
--inline-style
: usesstyles
option--inline-template
: uses thetemplate
option--spec false
: does not generate the test file
You can find the documentation for these options and more using
command: $ ng generate component help
Each time, the Angular CLI tool updates the app.module.ts
file. I
will go over these changes in the next
article.
Conclusion
Creating an Angular component by hand is not much work, especially when not using any external files.
The Angular CLI tool gives options to automatically create these files, even to the same file as one would create by hand.
In the next section, I will review the app.module.ts
file.