Component Directives
These directives are tied to the template (view) of a component, allowing it to control the display and functionality of the user interface.
Structural Directives
Structural directives modify the DOM structure. Examples include *ngFor
, *ngSwitch
, and *ngIf
, which add or remove elements based on conditions.
Attribute Directives
Attribute directives influence the behavior or appearance of DOM elements. Common examples are ngStyle
, ngModel
, and ngClass
.
Custom Directives
Custom directives can be created using the @Directive
decorator. The specific behavior is defined within the directive’s class
Example:
HTML
app.component.html
</pre></pre> div class="card"> <p>ngSwitch Example</p> <div class="card-body"> <label>Input string:</label> <input type="text" [(ngModel)]="num" /> <div [ngSwitch]="num"> <div *ngSwitchCase="'1'">One</div> <div *ngSwitchCase="'2'">Two</div> <div *ngSwitchCase="'3'">Three</div> <div *ngSwitchCase="'4'">Four</div> <div *ngSwitchCase="'5'">Five</div> <div *ngSwitchDefault>This is Default</div> </div> </div> <p>ngFor and ngIf Example</p> <div *ngFor="let emp of employee"> <ng-container *ngIf="emp.age >= 30"> <p>{{ emp.name }}: {{ emp.age }}</p> </ng-container> </div> <!-- Attribute Directive: [ngStyle] --> <p [ngStyle]="{ 'color': 'blue', 'font-size': '12px' }"> ngStyle Example </p> <!-- Custom Directive: ng g directive uppercase --> <div> <input type="text" appUppercase placeholder="Enter text" /> </div> </div>
Javascript:
import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'AngularApplication'; num: number = 0; employees: Employee[] = [ { name: 'John', age: 30 }, { name: 'Jane', age: 37 }, { name: 'Doe', age: 26 } ]; } class Employee { name: string; age: number; }
Now, let’s switch from directives to services, which allow you to manage the logic and behavior of your Angular apps.
Services
A service class is created for information or logic that isn’t related to a particular view and that you wish to distribute throughout components. The service class declaration comes right before the @Injectable decorator.
The metadata needed to inject your service as a dependency into client components is provided by the decorator. To improve modularity and reusability, Angular separates components from services. As shown in the image below :
You can create lean and effective component classes by isolating the view-related functionality of a component from other types of processing.
Example: counter.service.ts
Javascript:
import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root', }) export class CounterManager { private value = 0; increase(): void { this.value++; } retrieveValue(): number { return this.value; } }
To improve the separation of concerns, let’s go deeper into Dependency Injection (DI), which is critical for maintaining lean and modular components.
Dependency Injection(DI)
Dependency injection (DI) enables you to maintain the efficiency and leanness of your component classes. DI assigns these responsibilities to the services rather than doing them themselves. DI does not get data from a server, verify user input, or log directly to the console.
DI is used everywhere to give new components the services or other things they require, and it is hooked into an Angular framework. As you can see in the image below, Services are consumed by components; that is, a service can be injected into a component to grant it access to that service class.
Next, we’ll look at one of Angular’s most useful features: the Router. This allows for simple navigation without having to reload the page.
The Router
Additionally, it offers preloading techniques to maximize performance, tools for managing lazy loading, and guarantees quicker load times. Developers may produce scalable, maintainable apps with responsive interfaces and clear navigation by utilizing the Angular Router.
Javascript:
import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import { EmployeeListComponent } from './employee-list/employee-list.component'; import { CreateEmployeeComponent } from './create-employee/create-employee.component'; import { UpdateEmployeeComponent } from './update-employee/update-employee.component'; import { EmployeeDetailsComponent } from './employee-details/employee-details.component'; const appRoutes: Routes = [ { path: 'employee-list', component: EmployeeListComponent }, { path: 'add-employee', component: CreateEmployeeComponent }, { path: '', redirectTo: 'employee-list', pathMatch: 'full' }, { path: 'edit-employee/:id', component: UpdateEmployeeComponent }, { path: 'employee-info/:id', component: EmployeeDetailsComponent } ]; @NgModule({ imports: [RouterModule.forRoot(appRoutes)], exports: [RouterModule] }) export class MainRoutingModule { }
Let’s move on to talk about Angular state management and how RxJS helps with reactive architecture.
State Management
In Angular, RxJS (Reactive Extensions for JavaScript) is often used to handle state management because it is great at handling actions that happen at different times. RxJS is perfect for activities like HTTP requests, user interactions, and real-time updates because it offers Observables, which effectively handle streams of data and events.
Developers can ensure a more responsive and maintainable application state by utilizing RxJS operators and subjects to design reactive patterns. In an Angular application, this method guarantees smooth communication between various components and services and improves scalability.
Finally, we’ll look at Angular’s HTTP Client, which is a useful tool for dealing with backend services and APIs.
HTTP Client
In Angular, the HttpClient is used to send HTTP queries to backend services and APIs. Using functions like get(), post(), put(), and delete(), makes tasks like retrieving data, completing forms, or modifying information easier.
Reactive programming using RxJS is supported by HttpClient, enabling developers to effectively manage asynchronous data streams.
It is an effective tool for creating dynamic and data-driven applications since it also makes it possible to customize HTTP headers, query parameters, and centralized error handling via interceptors.
Key Features of HttpClient:
Example: post-list.component.ts
javascript
import { Component, OnInit } from '@angular/core'; import { HttpClient } from '@angular/common/http'; @Component({ selector: 'app-post-list', templateUrl: './post-list.component.html', styleUrls: ['./post-list.component.css'], }) export class PostListComponent implements OnInit { posts: any[] = []; // Array to store the retrieved posts constructor(private httpClient: HttpClient) {} ngOnInit(): void { this.httpClient .get&lt;any[]&gt;('https://jsonplaceholder.typicode.com/posts') .subscribe((response) =&gt; { this.posts = response; // Assign fetched data to the posts array }); } }
Conclusion
The solid structure of Angular makes it a great tool for creating dynamic and expandable web apps. Developers can construct smooth and effective user experiences with its modular design, component usage, directives, services, and dependency injection.
Whether you’re working on large-scale projects or single-page apps, Angular’s extensive ecosystem makes development easier while guaranteeing performance and maintainability.
Consider taking an Angular JS course if you’re prepared to learn Angular and develop your web development skills. You will acquire the abilities required to develop significant web solutions and maintain your competitive edge in the tech sector through expert-led instruction and practical assignments. Begin your educational path right now!
Frequently asked questions:
1. Is Angular based on MVC or MVVM?
The main foundation of Angular is the MVC (Model-View-Controller) architecture, in which the Controller links the View, the Model handles data, and the View controls the user experience. However, It is a combination of both patterns because of its component-based structure and two-way data binding, which also fits with the ideas of MVVM (Model-View-ViewModel).
2. Is Angular A MVC Architecture?
Angular uses a component-based framework while adhering to a hybrid Model-View-Controller (MVC) architecture. Its components function as both the Controller and the View in place of a conventional MVC design, which simplifies development while preserving the separation of concerns.
3. Is AngularJS based on architecture?
AngularJS is built on top of the Model-View-Controller (MVC) architecture, in which the Controller handles user interactions, the View shows data, and the Model manages data. It does, however, modify MVC to fit its declarative programming approach and dynamic two-way data binding.