A component is the most basic UI building block of an Angular app. It is a class that controls a specific part of the user interface, which includes:
- An HTML template
- CSS Styles
- Logic in JavaScript/Typescript
A component’s template defines the layout and structure of the UI element, the styles determine its appearance, and the logic controls its behavior.
Components can be used to build up larger parts of an application by composing multiple components together. This allows you to use them to easily build and maintain complex applications which are organized in a clear separation of concerns fashion.
Components are defined using the @Component
decorator, which is provided by the @angular/core
module. The decorator is used to provide metadata about the component, such as its selector, template, and styles.
Example:
import { Component } from '@angular/core'; @Component({ selector: 'app-welcome', templateUrl: './welcome.component.html', styleUrls: ['./welcome.component.css'] }) export class WelcomeComponent { show = false; message = 'Welcome to Angular components'; showWelcomeMessage() { this.show = true; } }
Based on the code above you can see that the WelcomeComponent has the selector app-welcome, the component template can be found within the same location in a file named welcome.component.html, and the component styles in another file within the same location named welcome.component.css.
An example template file would look like below:
<button (click)="showWelcomeMessage()">Show welcome message</button> <p *ngIf="show">{{ message }}</p>
An example component style would be a simple .css file that has some code in it.
button { color: #fff; background-color: #5cb85c; border-color: #4cae4c; }
The code above will make the button in welcome.component.html green and the text of the button (“Show welcome message”) white.
You can check the result by navigating to this link – https://angular-ivy-oc2tqw.stackblitz.io
If you want to learn more you can check out this tutorial.
Check out the full course here