Components
Components are the main building blocks of Angular applications. Each component represents a part of a larger web page. Organizing an application into components helps provide structure to your project, clearly separating code into specific parts that are easy to maintain and grow over time.
Defining a component
Every component has a few main parts:
- A
@Componentdecorator that contains some configuration used by Angular. - An HTML template that controls what renders into the DOM.
- A CSS selector that defines how the component is used in HTML.
- A TypeScript class with behaviors, such as handling user input or making requests to a server.
Here is a simplified example of a UserProfile component.
// user-profile.ts
@Component({
selector: 'user-profile',
template: `
<h1>User profile</h1>
<p>This is the user profile page</p>
`,
})
export class UserProfile {
/* Your component code goes here */
}The @Component decorator also optionally accepts a styles property for any CSS you want to apply to your template:
// user-profile.ts
@Component({
selector: 'user-profile',
template: `
<h1>User profile</h1>
<p>This is the user profile page</p>
`,
styles: `
h1 {
font-size: 3em;
}
`,
})
export class UserProfile {
/* Your component code goes here */
}Separating HTML and CSS into separate files
You can define a component's HTML and CSS in separate files using templateUrl and styleUrl:
// user-profile.ts
@Component({
selector: 'user-profile',
templateUrl: 'user-profile.html',
styleUrl: 'user-profile.css',
})
export class UserProfile {
// Component behavior is defined in here
}<!-- user-profile.html -->
<h1>User profile</h1>
<p>This is the user profile page</p>/* user-profile.css */
h1 {
font-size: 3em;
}Using components
You build an application by composing multiple components together. For example, if you are building a user profile page, you might break the page up into several components like this:
flowchart TD
A[UserProfile]-->B
A-->C
B[UserBiography]-->D
C[ProfilePhoto]
D[UserAddress]Here, the UserProfile component uses several other components to produce the final page.
To import and use a component, you need to:
- In your component's TypeScript file, add an
importstatement for the component you want to use. - In your
@Componentdecorator, add an entry to theimportsarray for the component you want to use. - In your component's template, add an element that matches the selector of the component you want to use.
Here's an example of a UserProfile component importing a ProfilePhoto component:
// user-profile.ts
import {ProfilePhoto} from 'profile-photo.ts';
@Component({
selector: 'user-profile',
imports: [ProfilePhoto],
template: `
<h1>User profile</h1>
<profile-photo />
<p>This is the user profile page</p>
`,
})
export class UserProfile {
// Component behavior is defined in here
}Next Step
Now that you know how components work in Angular, it's time to learn how we add and manage dynamic data in our application.