Components
Components are the building blocks of Angular applications, comprising a template, class, and metadata. They encapsulate reusable UI elements and their associated logic.
A component comprises three main parts:
- Template: Defines the HTML markup that represents the view of the component.
- Class: Contains the logic and properties associated with the component.
- Metadata: Specifies additional information about the component, such as its selector, styles, and dependencies.
Syntax:
@Component({
selector: 'app-example',
templateUrl: './example.component.html',
styleUrls: ['./example.component.css']
})
export class ExampleComponent {
// Component logic and properties
}
Features of Components:
- Components encapsulate reusable UI elements along with their logic.
- They have their own template, class, and metadata.
- Components can communicate with other components using input and output properties.
- They follow a hierarchical structure and can be nested within one another.
- Lifecycle hooks allow developers to execute code at specific stages of a component’s lifecycle.
Code Example:
To create a new component in Angular use the following command.
ng generate component counter
<!-- counter.component.html -->
<button (click)="increment()">
Increment
</button>
<div>{{ count }}</div>
<button (click)="decrement()">
Decrement
</button>
<!-- app.component.html -->
<div class="container">
<h1>w3wiki</h1>
<h3>
Difference between Component and Module
</h3>
<app-counter> </app-counter>
</div>
//counter.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-counter',
templateUrl: './counter.component.html',
styleUrls: ['./counter.component.css'],
})
export class CounterComponent {
count = 0;
increment() {
this.count++;
}
decrement() {
this.count--;
}
}
//app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent { }
Output:
Difference between directives and components
In Angular, directives, and components are essential concepts that help to build dynamic and interactive web applications. While they both play significant roles, understanding their differences and use cases is crucial for effective Angular development.