Explain Angular Component Lifecycle Hooks
Angular Component Lifecycle Hooks are special methods provided by Angular that allow developers to perform actions at different stages of a component's life.
A component goes through different stages such as creation, change detection, and destruction. Lifecycle hooks allow us to execute code at these stages.
Important Lifecycle Hooks
ngOnInit() runs when the component is initialized or created. It is commonly used for loading data, initializing variables, and calling APIs.
ngOnInit() {
console.log("Component started");
}
ngOnChanges() runs when a value received by the component changes. It is useful when a component receives data from another component and that data changes.
ngOnChanges() {
console.log("Value changed");
}
ngDoCheck() is used when Angular performs change checking. It allows the developer to perform custom checking when changes need to be detected.
ngDoCheck() {
console.log("Checking changes");
}
ngOnDestroy() runs just before the component is removed or destroyed. It can be used to perform cleanup operations before the component is removed.
ngOnDestroy() {
console.log("Component removed");
}
Summary Table
| Lifecycle Hook | When it runs | Main Purpose |
|---|---|---|
| ngOnInit() | When component is initialized | Load data, initialize variables, call API |
| ngOnChanges() | When received value changes | Respond to changed input data |
| ngDoCheck() | During Angular change checking | Perform custom change checking |
| ngOnDestroy() | Before component is removed | Cleanup before destruction |
Explain Angular Directives — *ngIf, *ngFor, *ngSwitch, ngClass
Directives are special instructions in Angular that are used to change the behavior, structure, or appearance of HTML elements dynamically. Angular directives can be broadly used to control how elements are displayed and how they behave.
*ngIf is a structural directive used to show or hide an HTML element based on a condition.
<p *ngIf="isLoggedIn">
Welcome User
</p>
If isLoggedIn is true, the paragraph is displayed; otherwise, it is not displayed.
*ngFor is a structural directive used to repeat an HTML element for each item in a collection.
<ul>
<li *ngFor="let student of students">
{{ student }}
</li>
</ul>
Here, the <li> element is repeated for every student in the students collection.
*ngSwitch is used when there are multiple possible choices. It works with *ngSwitchCase, which defines individual cases, and *ngSwitchDefault, which executes when no case matches.
<div [ngSwitch]="day">
<p *ngSwitchCase="'Monday'">Start of week</p>
<p *ngSwitchCase="'Friday'">End of week</p>
<p *ngSwitchDefault>Other day</p>
</div>
The appropriate content is displayed based on the value of day.
ngClass is an attribute directive used to add or remove CSS classes dynamically based on a condition.
<p [ngClass]="isSuccess ? 'success' : 'danger'">
Result
</p>
If isSuccess is true, the success CSS class is applied; otherwise, the danger class is applied.
Summary
| Directive | Type | Purpose |
|---|---|---|
| *ngIf | Structural | Shows or hides elements based on a condition |
| *ngFor | Structural | Repeats elements for each item in a collection |
| *ngSwitch | Structural | Selects content from multiple choices |
| ngClass | Attribute | Dynamically adds or removes CSS classes |
Explain Data Binding in Angular
Data Binding in Angular is a mechanism used to establish a connection between the component's TypeScript data and the HTML template. It allows data to be displayed in the UI and allows user actions to interact with component data.
Angular provides four main types of data binding.
Interpolation is used to display TypeScript data in the HTML template.
Syntax{{ expression }}
Example
name = "Farhan";
<p>Student Name: {{ name }}</p>
The value of name is displayed in the HTML.
Property binding is used to set an HTML element's property using a TypeScript value.
Syntax[property]="value"
Example
<button [disabled]="isDisabled">
Submit
</button>
Here, the disabled property of the button is controlled by the isDisabled variable.
Event binding is used to handle user actions or events and call a method in the component.
Syntax(event)="method()"
Example
<button (click)="showMessage()">
Click Me
</button>
When the button is clicked, the showMessage() method is called. Common events include (click), (mouseenter), (mouseleave), (input), (change), and (submit).
Two-way data binding allows data to flow in both directions between the component and the HTML template. It uses [(ngModel)].
<input [(ngModel)]="name">
<p>Hello {{ name }}</p>
When the user changes the input, the name variable is updated, and changes to name are reflected back in the input.
Summary Table
| Type | Syntax | Purpose |
|---|---|---|
| Interpolation | {{ }} | Displays component data |
| Property Binding | [ ] | Sets HTML properties |
| Event Binding | ( ) | Handles user events |
| Two-Way Binding | [(ngModel)] | Synchronizes data in both directions |
Explain Angular Built-in Pipes
Pipes in Angular are used to change or transform data before displaying it in the HTML template. They are written using the pipe symbol |.
{{ value | pipe }}
Angular provides several built-in pipes for common data transformations.
Common Built-in Pipes
{{ name | uppercase }} — Example: farhan → FARHAN{{ "HELLO" | lowercase }} — Output: hello{{ name | titlecase }}{{ price | currency }} — For Indian Rupees: {{ price | currency:'INR' }}{{ today | date:'dd/MM/yyyy' }}{{ result | percent }}{{ name | slice:0:3 }} — displays characters from index 0 up to index 3.Summary Table
| Pipe | Purpose | Example |
|---|---|---|
| uppercase | Converts text to uppercase | {{ name | uppercase }} |
| lowercase | Converts text to lowercase | {{ name | lowercase }} |
| titlecase | Converts text to title case | {{ name | titlecase }} |
| currency | Formats currency | {{ price | currency:'INR' }} |
| date | Formats dates | {{ today | date:'dd/MM/yyyy' }} |
| percent | Formats percentage | {{ result | percent }} |
| slice | Extracts a portion of data | {{ name | slice:0:3 }} |
Custom Pipe
Angular also allows developers to create custom pipes. A custom pipe can be generated using:
ng generate pipe greeting
or
ng g pipe greeting
Explain Forms and Form Validation in Angular
Forms in Angular are used to collect user input and process data submitted by the user. Angular provides two main approaches for creating forms: Template-driven forms and Reactive forms.
Form validation is used to ensure that the data entered by the user satisfies required conditions such as required, email, minlength, and pattern.
In template-driven forms, most of the form is controlled from the HTML template. It is simpler and suitable for basic forms. It uses ngForm and ngModel.
<form #studentForm="ngForm"
(ngSubmit)="submitForm(studentForm)">
<label>Name:</label>
<input type="text" name="studentName" ngModel>
<button type="submit">Submit</button>
</form>
TypeScript
submitForm(studentForm: any) {
console.log(studentForm.value);
}
Here, #studentForm creates a template reference, ngForm tells Angular to treat the form as an Angular form, ngModel binds the input to the form, and ngSubmit handles form submission.
In reactive forms, the form structure and controls are mainly created and managed in the TypeScript file. It uses FormGroup and FormControl.
<form [formGroup]="studentForm"
(ngSubmit)="submitForm()">
<input formControlName="studentName">
<input formControlName="email">
<button type="submit">Submit</button>
</form>
TypeScript
studentForm = new FormGroup({
studentName: new FormControl(''),
email: new FormControl('')
});
submitForm() {
console.log(this.studentForm.value);
}
Reactive forms are more structured and are suitable for complex forms.
Form Validation
Form validation checks whether the data entered by the user is valid according to specified rules. These validations can be used to prevent invalid or incomplete data from being submitted.
Template-Driven vs Reactive Forms
| Feature | Template-Driven | Reactive |
|---|---|---|
| Main control | HTML template | TypeScript |
| Commonly uses | ngModel | FormControl, FormGroup |
| Complexity | Simple | More structured |
| Code | Less code | More code |
| Suitable for | Simple forms | Complex forms |
Explain Modules in Angular with Example
Modules in Angular are used to group related components, services, and other application features together. They help organize an Angular application into manageable parts.
Angular applications can have a root module (AppModule) and additional feature modules for specific parts of the application.
Types of Modules
Example
A simple module can be defined using @NgModule:
import { NgModule } from '@angular/core';
@NgModule({
declarations: [],
imports: [],
providers: [],
bootstrap: []
})
export class AppModule {
}
Here, @NgModule defines the Angular module and its configuration.
Simple Structure
Angular Application
|
AppModule
|
┌───┴────┐
| |
Student Course
Module Module
| |
Components Components
Thus, modules provide a way to organize related functionality into separate sections of an Angular application.
Explain Services and Dependency Injection in Angular
An Angular Service is a class used to store reusable data and functionality that can be shared by different components. Services help avoid repeating the same code in multiple components.
A service can be created using the Angular CLI:
ng generate service student
or:
ng g service student
Example of a Service
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class StudentService {
getStudent() {
return "Farhan";
}
}
Here, StudentService contains the reusable getStudent() method. The providedIn: 'root' configuration makes the service available throughout the application.
Dependency Injection is a mechanism in Angular through which Angular provides a required service to a component instead of the component creating the service itself. This makes components easier to manage and allows them to use reusable services.
Exampleimport { StudentService } from './student.service';
constructor(private studentService: StudentService) {
}
Here, StudentService is injected into the component through the constructor. Angular provides the required service automatically.
Working
The basic working can be represented as:
Component
|
| requests service
↓
Dependency Injection
|
| provides
↓
StudentService
|
↓
Reusable Data / Functionality
Advantages
Explain Routing and Navigation in Angular
Routing in Angular is used to navigate between different views or components of an application. It allows users to move from one page/component to another without reloading the entire browser page. Angular routing is especially useful for building Single Page Applications (SPAs).
Working of Routing
Angular routing connects a URL path with a particular component. For example:
URL Component
------------------------------------------------
/home → HomeComponent
/student → StudentComponent
/about → AboutComponent
When the user navigates to a particular URL, Angular displays the corresponding component without refreshing the complete webpage.
Example
A simple routing configuration can be represented as:
const routes = [
{ path: 'home', component: HomeComponent },
{ path: 'student', component: StudentComponent },
{ path: 'about', component: AboutComponent }
];
Here, home displays HomeComponent, student displays StudentComponent, and about displays AboutComponent.
Navigation can then be provided through links such as:
<a routerLink="/home">Home</a>
<a routerLink="/student">Student</a>
<a routerLink="/about">About</a>