The fundamental building block for creating applications in Angular.
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.
Every component has a few main parts:
@Componentdecorator that contains some configuration used by Angular.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 */}
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;}
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:
Here, the UserProfile component uses several other components to produce the final page.
To import and use a component, you need to:
import statement for the component you want to use.@Component decorator, add an entry to the imports array for the component you want to use.Here's an example of a UserProfile component importing a ProfilePhoto component:
// user-profile.tsimport {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}
TIP: Want to know more about Angular components? See the In-depth Components guide for the full details.
Now that you know how components work in Angular, it's time to learn how we add and manage dynamic data in our application.