Build Your First Angular Application for Best Practice
Build Your First Angular Application : Although creating your first Angular application can seem overwhelming, it can be doable and even pleasant if you take a step-by-step approach. With an emphasis on best practices and CRUD operations, this article will lead you through the process of building an Angular application with Angular Material. You will have a completely working Angular application in the conclusion, along with a good grasp of its parts and structure.
Developing your First Angular Application is a big step in your development career. Although there will be obstacles along the way, taking a methodical approach will make the process easier and more enjoyable. This all-inclusive tutorial will enable you to use Angular Material to build your First Angular Application, focusing on best practices and implementing necessary CRUD functions. At the end, you will have created a stable First Angular Application with a well-organized architecture and unified user interface.
Starting Your First Angular Application Project :
1. Introduction to Angular
Angular is a popular framework for building dynamic web applications. It provides a robust set of tools and features that make it easier to develop, maintain, and scale your web applications. Angular Material is a UI component library for Angular developers that implements Google's Material Design.
Key Features of Angular:
Key Features of Angular Material:
2. Setting Up Your Environment
Before we start building the application, we need to set up the development environment.
Prerequisites:
To install Angular CLI, open your terminal and run:
npm install -g @angular/cli
3. Creating a New Angular Project
Once the environment is set up, you can create a new Angular project.
Step-by-Step Instructions:
ng new my-app
You will be prompted to choose a stylesheet format. Select CSS.
cd my-app
ng serve
Open your browser and navigate to https://localhost:4200/. You should see the Angular welcome page.
4. Adding Angular Material
Angular Material provides modern UI components that follow Material Design guidelines. Let's add Angular Material to our project.
Step-by-Step Instructions:
ng add @angular/material
You will be prompted to choose a theme, set up global typography, and include animations. Select the defaults for now.
import { MatButtonModule } from '@angular/material/button';
import { MatInputModule } from '@angular/material/input';
import { MatCardModule } from '@angular/material/card';
import { MatToolbarModule } from '@angular/material/toolbar';
import { MatTableModule } from '@angular/material/table';
import { MatIconModule } from '@angular/material/icon';
@NgModule({
imports: [
MatButtonModule,
MatInputModule,
MatCardModule,
MatToolbarModule,
MatTableModule,
MatIconModule,
// other imports
],
// other configurations
})
export class AppModule { }
5. Building the Application Structure
Now that we have Angular Material set up, let's build the application structure. Our application will have the following components:
Step-by-Step Instructions:
ng generate component header
ng generate component home
ng generate component item
import { HeaderComponent } from './header/header.component';
import { HomeComponent } from './home/home.component';
import { ItemComponent } from './item/item.component';
@NgModule({
declarations: [
HeaderComponent,
HomeComponent,
ItemComponent,
// other declarations
],
// other configurations
})
export class AppModule { }
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { ItemComponent } from './item/item.component';
const routes: Routes = [
{ path: '', component: HomeComponent },
{ path: 'items', component: ItemComponent },
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
<app-header></app-header>
<router-outlet></router-outlet>
<mat-toolbar color="primary">
<span>My App</span>
<span class="spacer"></span>
<button mat-button routerLink="/">Home</button>
<button mat-button routerLink="/items">Items</button>
</mat-toolbar>
.spacer {
flex: 1 1 auto;
}
6. Implementing CRUD Operations
We will now implement CRUD (Create, Read, Update, Delete) operations in the ItemComponent.
Step-by-Step Instructions:
ng generate service item
export interface Item {
id: number;
name: string;
description: string;
}
import { Injectable } from '@angular/core';
import { Item } from './item.model';
import { of, Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class ItemService {
private items: Item[] = [
{ id: 1, name: 'Item 1', description: 'Description 1' },
{ id: 2, name: 'Item 2', description: 'Description 2' }
];
getItems(): Observable<Item[]> {
return of(this.items);
}
getItem(id: number): Observable<Item> {
const item = this.items.find(i => i.id === id);
return of(item!);
}
addItem(item: Item): void {
this.items.push({ ...item, id: this.items.length + 1 });
}
updateItem(updatedItem: Item): void {
const index = this.items.findIndex(i => i.id === updatedItem.id);
if (index !== -1) {
this.items[index] = updatedItem;
}
}
deleteItem(id: number): void {
this.items = this.items.filter(i => i.id !== id);
}
}
<div class="item-container">
<mat-card>
<form (ngSubmit)="onSubmit()">
<mat-form-field>
<input matInput placeholder="Name" [(ngModel)]="item.name" name="name" required>
</mat-form-field>
<mat-form-field>
<input matInput placeholder="Description" [(ngModel)]="item.description" name="description" required>
</mat-form-field>
<button mat-raised-button color="primary" type="submit">Save</button>
</form>
</mat-card>
<mat-table [dataSource]="items" class="mat-elevation-z8">
<ng-container matColumnDef="name">
<mat-header-cell *matHeaderCellDef> Name
</mat-header-cell>
<mat-cell *matCellDef="let item"> {{item.name}} </mat-cell>
</ng-container>
<ng-container matColumnDef="description">
<mat-header-cell *matHeaderCellDef> Description </mat-header-cell>
<mat-cell *matCellDef="let item"> {{item.description}} </mat-cell>
</ng-container>
<ng-container matColumnDef="actions">
<mat-header-cell *matHeaderCellDef> Actions </mat-header-cell>
<mat-cell *matCellDef="let item">
<button mat-icon-button (click)="editItem(item)">
<mat-icon>edit</mat-icon>
</button>
<button mat-icon-button (click)="deleteItem(item.id)">
<mat-icon>delete</mat-icon>
</button>
</mat-cell>
</ng-container>
<mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
<mat-row *matRowDef="let row; columns: displayedColumns;"></mat-row>
</mat-table>
</div>
.item-container {
max-width: 600px;
margin: 20px auto;
}
import { Component, OnInit } from '@angular/core';
import { Item, ItemService } from '../item.service';
@Component({
selector: 'app-item',
templateUrl: './item.component.html',
styleUrls: ['./item.component.css']
})
export class ItemComponent implements OnInit {
items: Item[] = [];
item: Item = { id: 0, name: '', description: '' };
displayedColumns: string[] = ['name', 'description', 'actions'];
constructor(private itemService: ItemService) {}
ngOnInit(): void {
this.getItems();
}
getItems(): void {
this.itemService.getItems().subscribe(items => this.items = items);
}
onSubmit(): void {
if (this.item.id) {
this.itemService.updateItem(this.item);
} else {
this.itemService.addItem(this.item);
}
this.getItems();
this.resetForm();
}
editItem(item: Item): void {
this.item = { ...item };
}
deleteItem(id: number): void {
this.itemService.deleteItem(id);
this.getItems();
}
resetForm(): void {
this.item = { id: 0, name: '', description: '' };
}
}
7. Styling with Angular Material
To give our application a polished look, we will style it using Angular Material.
Step-by-Step Instructions:
@import "~@angular/material/prebuilt-themes/indigo-pink.css";
body {
margin: 0;
font-family: Roboto, "Helvetica Neue", sans-serif;
}
Well done on utilizing Angular Material to create your first Angular application and integrating CRUD functions! This application demonstrates how to use Angular Material for a unified user interface, organize your first Angular application, and incorporate basic CRUD features.
You can make sure that your First Angular Application is not only reliable but also scalable, manageable, and intuitive by following best practices. Explore Angular's rich feature set and documentation in further detail to advance your knowledge and talents during the development of your first Angular application.
Other :
Flutter Devloper
8 个月Any opportunity for internship?