Creating components
In Angular, a component is a building block for creating web applications. It consists of a template, which defines the structure and layout of the component, and a TypeScript class, which provides the component's behavior and logic.
Creating a New Component
To create a new component, you can use the Angular CLI command:
ng generate component my-component
This will create a new directory named my-component
with four files:
my-component.component.ts
- the TypeScript class for the componentmy-component.component.html
- the HTML template for the componentmy-component.component.css
- the CSS stylesheet for the componentmy-component.component.spec.ts
- the unit test for the component
Defining the Component's Template
The HTML template for a component is defined in a separate file, which makes it easier to manage and reuse. You can use standard HTML tags and Angular directives to define the layout and content of the template.
Here's an example of a template for a simple component that displays a message:
<div>
<h1>{{ title }}</h1>
<p>{{ message }}</p>
</div>
In this example, we're using the double curly braces notation {{ }}
to display the values of two properties: title
and message
.
Defining the Component's Class
The TypeScript class for a component provides the component's behavior and logic. It defines the properties and methods that are used by the template.
Here's an example of a TypeScript class for the simple component we defined earlier:
import { Component } from '@angular/core';
@Component({
selector: 'app-my-component',
templateUrl: './my-component.component.html',
styleUrls: ['./my-component.component.css']
})
export class MyComponentComponent {
title = 'My Component';
message = 'Hello, world!';
}
In this example, we're using the @Component
decorator to define the selector, template, and stylesheet for the component. We're also defining two properties, title
and message
, which are used in the template.
Using the Component in a Template
Once you've defined a component, you can use it in other templates by adding the component's selector as a custom HTML tag. Here's an example of using our MyComponent
component in another template:
<app-my-component></app-my-component>
This will render the template defined in my-component.component.html
and use the properties and methods defined in MyComponentComponent
.
Conclusion
Creating components is a fundamental part of building web applications with Angular. By separating the template and class into separate files, you can create reusable and maintainable components that can be easily composed into larger applications.
Book a conversation with us for personalize training today!