Angular is a TypeScript - based open - source web application framework maintained by Google. It provides a structured way to build single - page applications (SPAs). At its core, Angular follows the Model - View - Controller (MVC) or more precisely, the Model - View - ViewModel (MVVM) architectural pattern.
Components are the building blocks of an Angular application. A component controls a patch of the screen called a view. Each component consists of a TypeScript class with a @Component
decorator that defines the metadata such as the selector, template, and styles.
import { Component } from '@angular/core';
@Component({
selector: 'app - hello - world',
template: '<h1>Hello, World!</h1>',
styleUrls: ['./hello - world.component.css']
})
export class HelloWorldComponent {
constructor() { }
}
In this example, the HelloWorldComponent
is a simple Angular component with a basic template that displays “Hello, World!”.
Angular applications are modular. An Angular module is a container for a cohesive block of code dedicated to an application domain, a workflow, or a closely related set of capabilities. Modules group components, directives, pipes, and services.
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform - browser';
import { HelloWorldComponent } from './hello - world.component';
@NgModule({
declarations: [
HelloWorldComponent
],
imports: [
BrowserModule
],
providers: [],
bootstrap: [HelloWorldComponent]
})
export class AppModule { }
Services are used to share data and logic across different components. They are singletons in Angular applications. For example, a data service can be used to fetch data from an API and make it available to multiple components.
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class DataService {
constructor(private http: HttpClient) { }
getData() {
return this.http.get('https://api.example.com/data');
}
}
npm install -g @angular/cli
ng new my - angular - project
cd my - angular - project
ng serve
You can create a new component using the Angular CLI. For example, to create a new component named user - profile
, run the following command:
ng generate component user - profile
This will generate a set of files for the component including a TypeScript file, an HTML template file, a CSS file, and a test file.
Let’s assume we have the DataService
defined above. Here’s how we can use it in a component:
import { Component } from '@angular/core';
import { DataService } from '../data.service';
@Component({
selector: 'app - data - consumer',
template: '<div>{{data | json}}</div>'
})
export class DataConsumerComponent {
data;
constructor(private dataService: DataService) {
this.dataService.getData().subscribe((response) => {
this.data = response;
});
}
}
Routing is a common practice in Angular applications to navigate between different views. You can define routes in the app - routing.module.ts
file.
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { HomeComponent } from './home.component';
import { AboutComponent } from './about.component';
const routes: Routes = [
{ path: '', component: HomeComponent },
{ path: 'about', component: AboutComponent }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
Reactive forms in Angular provide a more programmatic way to handle form data. Here is a simple example of a reactive form:
import { Component } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';
@Component({
selector: 'app - reactive - form',
template: `
<form [formGroup]="myForm">
<input type="text" formControlName="name">
<button [disabled]="!myForm.valid">Submit</button>
</form>
`
})
export class ReactiveFormComponent {
myForm: FormGroup;
constructor() {
this.myForm = new FormGroup({
name: new FormControl('', Validators.required)
});
}
}
const routes: Routes = [
{
path: 'lazy',
loadChildren: () => import('./lazy - module/lazy - module.module').then(m => m.LazyModuleModule)
}
];
TestBed
to create a testing environment for components.import { ComponentFixture, TestBed } from '@angular/core/testing';
import { HelloWorldComponent } from './hello - world.component';
describe('HelloWorldComponent', () => {
let component: HelloWorldComponent;
let fixture: ComponentFixture<HelloWorldComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [ HelloWorldComponent ]
})
.compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(HelloWorldComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
Angular is a powerful and comprehensive JavaScript framework that offers a structured way to build complex web applications. Its modular architecture, component - based design, and rich set of features make it suitable for large - scale projects. By understanding its fundamental concepts, usage methods, common practices, and best practices, developers can effectively use Angular to create efficient, maintainable, and high - performance web applications. Whether it’s handling routing, forms, or sharing data between components, Angular provides the necessary tools and patterns to streamline the development process.
In summary, Angular is a framework that empowers developers to build modern web applications with ease, but like any tool, it requires proper understanding and adherence to best practices for optimal results.