AI Hints
Home›Angular Tutorial›Property Binding, Event Binding and ng generate component
Angular · Lesson 24 of 120

ng generate component

The CLI does the typing.

⏱ 2 min read▶ Video at 29:18🎓 Free
Watch this lesson in the Angular courseWatch on YouTube ↗Full Angular course

Creating a component by hand means three files, and some boiler plate. The CLI can do it for us, in one command.

  • Three files
  • Boiler plate
  • One command

Generating a book card

Inside the project, ng generate component, then a name, creates a new component. We call it book card. The CLI creates four files, in their own folder. A ts file, an html file, a css file, and a test file.

Terminal
cd shop
ng generate component book-card
CREATE src/app/book-card/book-card.css (0 bytes)
CREATE src/app/book-card/book-card.spec.ts (547 bytes)
CREATE src/app/book-card/book-card.ts (196 bytes)
CREATE src/app/book-card/book-card.html (24 bytes)
ls src/app/book-card
book-card.css
book-card.html
book-card.spec.ts
book-card.ts

book-card.ts

Here's the generated class. The selector is app dash book dash card, so that's its tag. Style url, and template url, point to its own files. And the class is called Book Card, ready for our code.

book-card.tstypescript
import { Component } from '@angular/core';

@Component({
  imports: [],
  selector: 'app-book-card',
  styleUrl: './book-card.css',
  templateUrl: './book-card.html',
})
export class BookCard {
}

Short versions

ng g c is short for ng generate component. The CLI can generate other things too, like services, and pipes. Names are written in kebab case, with dashes. The CLI turns book dash card into the class name Book Card.

keyvalue
Short formng g c book-card
Alsong g service, ng g pipe
Nameskebab-case: book-card
ClassBookCard

Summary

ng generate component creates a component's files, with a selector, and a class, ready to go. Next, using components together.

Key takeaways
  • ng generate component
  • ng g c
  • app-book-card
Next up: Using Components Together — components inside components