Git Tutorial

Multiple Components

Angular applications are built using components, which are the building blocks of the framework. A component in Angular controls a portion of the user interface and consists of a TypeScript class, an HTML template, and an optional CSS stylesheet. When building large applications, it’s common to divide the app into multiple components for better organization and reusability.

In this tutorial, we’ll create a simple Angular application with multiple components and demonstrate how to:

  1. Create new components.
  2. Use components in other components.
  3. Communicate between components using inputs and outputs.

Create Components

Use the Angular CLI to generate two components:

ng generate component header
ng generate component footer

This command creates the following structure for each component:

  • A TypeScript file (header.component.ts or footer.component.ts)
  • An HTML file (header.component.html or footer.component.html)
  • A CSS file (header.component.css or footer.component.css)
  • A spec file for testing (e.g., header.component.spec.ts)
  • Updates the AppModule by declaring the new components.

Modifying Component Templates

Header Component

Edit the header.component.html file:

<header>
  <h1>Welcome to My Angular App</h1>
</header>

Footer Component

Edit the footer.component.html file:

<footer>
  <p>&copy; 2024 My Angular App</p>
</footer>

To include the HeaderComponent and FooterComponent in the main AppComponent:

  1. Open app.component.html.
  2. Add the selectors of the components:
<app-header></app-header>
<div class="content">
  <p>Main content goes here.</p>
</div>
<app-footer></app-footer>

The app-header and app-footer tags correspond to the selector property defined in header.component.ts and footer.component.ts.

        1 thought on “Multiple Components”

        1. Pingback: What Is Angular - Tech Mentor

        Leave a Comment

        Your email address will not be published. Required fields are marked *