Generate an Angular Component
Learn how to create a new component using the Angular CLI.
Angular CLI
Section titled “Angular CLI”You’ve already used the CLI to run our application locally with the ng serve command in the Getting Started section.
Now use it to create a new component as the Angular CLI also provide a dedicated command to generate a new component, ng generate component.
Instructions
Section titled “Instructions”-
Run the following command in a terminal to generate a new component called
task-listTerminal window ng generate component task-listor the short version:
Terminal window ng g c task-list -
Look for the generated folder called
task-listin thesrc/appdirectory.src└─ app└─ task-list└─ task-list.ts└─ task-list.html└─ task-list.css
By default, the Angular CLI will create a folder for the component, so you do not have to create it manually.
Component Metadata
Section titled “Component Metadata”When opening the task-list.ts file, you can see the following code:
import { Component } from "@angular/core";
@Component({ selector: "app-task-list", imports: [], templateUrl: "./task-list.html", styleUrls: ["./task-list.css"],})export class TaskList {}The @Component decorator defines the component’s configuration metadata.
A decorator is a way to do meta-programming. They can modify their target (classes, methods, …), call other methods when the target is called, or add metadata intended for a framework. This last point corresponds to how we use them in Angular.
The selector property defines the component’s HTML tag name. By using this selector in an HTML Template (view), Angular creates and displays an instance of the component.
import { Component } from "@angular/core";
@Component({ selector: "app-task-list", imports: [], templateUrl: "./task-list.html", styleUrls: ["./task-list.css"],})export class TaskList {}The templateUrl property defines the location of the HTML Template (its view) for the component. This is the view that will be displayed when the CSS selector is used in another HTML Template.
import { Component } from "@angular/core";
@Component({ selector: "app-task-list", imports: [], templateUrl: "./task-list.html", styleUrls: ["./task-list.css"],})export class TaskList {}The styleUrls property defines the locations of the component’s CSS files. These styles will be applied to the component’s template. By default styles are scoped to only affect your componet: styling all button tags for example won’t affect other components.
import { Component } from "@angular/core";
@Component({ selector: "app-task-list", imports: [], templateUrl: "./task-list.html", styleUrls: ["./task-list.css"],})export class TaskList {}Global styles can be defined in the src/styles.css file.
In this chapter, you learned how to create a new component using the Angular CLI. You also remembered that the component’s view is its HTML Template and the component’s model is its TypeScript file.
Angular CLI Documentation: generating a component