In Angular, a
component is a fundamental building block of the application's user interface. It represents a part of the UI that controls a specific view and behavior. Components are typically composed of three main parts: the component class, the component template (HTML), and the component stylesheet (CSS).
Here's an example of an Angular component:
Suppose we want to create a simple component to display information about a user:
1. Create the component class:
// user.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-user', // The component selector used in HTML templates
templateUrl: './user.component.html', // The path to the HTML template file
styleUrls: ['./user.component.css'] // The path to the CSS styles for this component
})
export class UserComponent {
userName: string = 'test user';
age: number = 30;
}
2. Create the component template:
<!-- user.component.html -->
<div>
<h2>User Information</h2>
<p><strong>Name:</strong> {{ userName }}</p>
<p><strong>Age:</strong> {{ age }}</p>
</div>
3. Create the component stylesheet (optional):
/* user.component.css */
div {
border: 1px solid #ccc;
padding: 10px;
margin: 10px;
}
4. Register the component in the AppModule (or another relevant module):
// app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { UserComponent } from './user.component'; // Import the UserComponent
@NgModule({
imports: [BrowserModule],
declarations: [UserComponent], // Declare the UserComponent
bootstrap: [UserComponent] // Set the UserComponent as the bootstrap component
})
export class AppModule { }
Now, you can use the `app-user` selector in your application's HTML to display the user information:
<!-- app.component.html -->
<div>
<app-user></app-user> <!-- This will render the UserComponent -->
</div>
When the application runs, it will display the following output:
User Information
Name: test user
Age: 30
This is a basic example of an
Angular component, and in real-world applications, components are used extensively to build complex user interfaces by combining and nesting them as needed.