Angular is a powerful framework for building client-side applications, and components are at the heart of Angular development. In this enhanced guide, I'll walk you through creating a simple Angular component with Bootstrap styling, complete with code examples and instructions for capturing the UI output.
What is a Component in Angular?
A component in Angular is a self-contained, reusable piece of the user interface (UI). It consists of,
- TypeScript Class: Contains the logic for the component
- Template: Defines the HTML structure of the component
- Styles: CSS for the component
- Decorator (@Component): Links the TypeScript class to its template and provides metadata
Every Angular application has at least one component, called the root component (usually named AppComponent), which serves as the container for all other components.
Steps to Create a Component with Bootstrap
Step 1. Set Up Your Angular Project.
If you haven't already set up an Angular project, use the Angular CLI to create one,
Step 2. Add Bootstrap to Your Project.
Install Bootstrap using npm.
Then, open the angular.json file and add Bootstrap CSS to the styles array.
Step 3. Create a Header Component.
Let's create a HeaderComponent that displays a navigation bar with the eCart title.
Generate the Component
Use Angular CLI to generate the component.
This will create.
- src/app/header/header.component.ts
- src/app/header/header.component.html
- src/app/header/header.component.css
- src/app/header/header.component.spec.ts
Modify the Component Files
Update header.component.html.
Update header.component.ts
Add Bootstrap Icons (optional).
Install Bootstrap Icons
Add to angular.json
Step 4. Create a Product Card Component.
Let's create another component for displaying product cards.
Update product-card.component.ts
Update product-card.component.html
Step 5. Update the App Component.
Now, let's use these components in the main app component.
Update app.component.ts
Update app.component.html
Step 6. Run the Application.
Start the Angular development server.
Open your browser and navigate to http://localhost:4200. You should see the eCart header and product cards displayed with Bootstrap styling.
UI Screenshot Instructions
After running ng serve, your application should look like this.
![ecart]()
Complete Code Summary
app.module.ts
header.component.ts and Template
Already provided above.
product-card.component.ts and Template
Already provided above.
app.component.ts and Template
Already provided above.
Key Takeaways
- Components are the fundamental building blocks of Angular applications
- Bootstrap provides ready-to-use CSS classes for creating responsive layouts
- The @Input() decorator allows passing data from parent to child components
- The *ngFor directive is used for rendering lists of elements
- Components can be nested to create complex UIs from simple, reusable parts