Create your first component
- ✔️Generate a componentLearn how to create a new component using the Angular CLI.
- ✔️Display the componentLearn how to display the component HTML content in the application.
Angular CLI
You already used the CLI to serve the application locally with the ng serve
command in the Getting Started step. Now let’s use it to create a new component!
The Angular CLI provides a command to generate a new component with the ng generate component component-name
command.
🎓 Instructions
-
Run the following command in a terminal to generate a new component called task-list.
-
Check for a new folder called task-list in the
src/app
folder.
Component metadata
By opening the task-list.component.ts
file, you can see the following code:
The @Component decorator defines the metadata for the component.
The selector property defines the component’s CSS element selector. By using this selector in a template HTML file, Angular creates and displays an instance of the component.
The templateUrl property defines the HTML template file for the component. That’s the HTML template that will be displayed when the css selector is used in another HTML file.
The styleUrls property defines the CSS files for the component. These styles will be applied to the component HTML template.
Display the component
So far the application only displays the app component HTML content in the browser. You generated the new component but you need to display its HTML content by using its selector.
🎓 Instructions
-
Update the
src/app/app.component.html
file. -
Check out the changes in your browser.
// TODO add mention about appModule update
✔️ What you learned
In this chapter, you learned how to create a new component using the Angular CLI and how to use it in your application.
🚦 Quiz
What is the command to create a new component using the Angular CLI?
ng generate component task-list
ng new task-list
ng create component task-list
ng component task-list
What is the property used to define the component ‘app-task-list’?
name
selector
title
tag
is Angular CLI meant to only create components?
- Yes
- No
Given the component is generated with the command ng generate component task-list
, what is the name of the selector component?
app-task-list
task-list
app-task
task list
What the template term refers to in Angular?
- The component.ts file?
- The component.html file?