Component
Component Definition
Angular 20 (TypeScript with Decorators):
Angular components are defined using a TypeScript class decorated with @Component. The template (HTML) and styles (CSS) are typically defined in separate files and linked via the decorator. Angular 20 has also embraced "standalone components" which simplify their structure by removing the need for NgModules for individual components.
// my-component.component.ts
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-my-component', // Custom HTML tag
templateUrl: './my-component.component.html', // Path to HTML template
styleUrls: ['./my-component.component.css'], // Path to CSS styles
standalone: true // Making it a standalone component
})
export class MyComponent implements OnInit {
title = 'Angular 20 Component';
constructor() { }
ngOnInit(): void {
console.log('Component initialized!');
}
handleClick(): void {
this.title = 'Title Changed!';
}
}
<div>
<h1>{{ title }}</h1>
<button (click)="handleClick()">Click Me</button>
</div>
structural directives
extends HTML by allowing you to define a tag whose content is created and controlled by JavaScript code. Components can include styles
Angular's ng-container, ng-content, and ng-template are structural directives in Angular that help with content projection and template manipulation. Let me break them down for you:
ng-container:
ng-container is a grouping element that doesn't add any extra nodes to the DOM. It's useful when you need to apply structural directives (like *ngIf or *ngFor) without introducing additional HTML elements.
Example:
<ng-container *ngIf="condition">
<p>This content will be shown if the condition is true.</p>
<p>Multiple elements can be wrapped without adding extra DOM nodes.</p>
</ng-container>
ng-content:
ng-content is used for content projection. It allows you to insert content from a parent component into a child component's template.
Example: Parent component template:
<app-child>
<h2>This content will be projected</h2>
</app-child>
Child component template:
<div class="child-wrapper">
<ng-content></ng-content>
</div>
ng-template:
ng-template defines a template that is not rendered by default. It's often used with structural directives or programmatically rendered content.
Example:
<ng-template #loading>
<p>Loading...</p>
</ng-template>
<div *ngIf="data; else loading">
{{ data }}
</div>
Nested Components
How to call a function in another component
pass data to a Nested Component using @Input
the @Output decorator is used to pass data from a child to parent component using @Output
Component Life Cycle Hooks
Change Detection means updating the DOM whenever data is changed. In its default strategy, Angular will run the change detector to update the DOM whenever any data is mutated or changed.