This article will share with you a Angular practical experience to learn how to quickly develop a backend system using angualr combined with ng-zorro. I hope it will be helpful to everyone!
We have learned a lot about angular
in the past few days. This time we have a small finished product.
angualr
Combined with ng-zorro
to develop a backend system quickly and standardizedly. [Related tutorial recommendations: "angular tutorial"]
System functions include the following:
- Welcome page
- User list
- User added
- User modified
- User deleted
All services use simulated data.
Let’s do it as we are told.
Combined with ng-zorro
##angular The more popular
ui frameworks are:
- Angular Material officially designated UI framework
- NG-ZORRO, also known as Ant Design of Angular, the more popular domestic UI framework
Ant Design I believe people who do front-end development are familiar with it. So here we combine it with the
NG-ZORRO framework. If you are familiar with
Vue or
React version of
Ant Design, I believe you can connect seamlessly~
angular-cli to generate a project
ng-zorro.
ng-zorro is very simple: enter the
ng-zorro root directory and execute
ng add ng-zorro-antd That is Can.
Of course you can also executeCombinednpm install ng-zorro-antd
to add, but it is not recommended.
ng-zorro After completion, we run the project
npm run start, you will be in
http://localhost:4200 page, see the content below.
Not Bad, Bro.
Configure routing
We changed it tohash routing and added user routing. The scaffolding has done it for us, we only need to make some minor modifications.
- First add the page
user
User's list page, use
ng-zorroin
tableComponent
- The user's new and modified pages can share the same page, using the
form
component## in
ng-zorro #The page deletion function directly uses the pop-up prompt, using the - modal
component in
ng-zorro
Introduce the - ng-zorro
component as needed
Adjust the routing file - According to the idea, we have to
introduces: <pre class='brush:php;toolbar:false;'>// app.module.ts
import { ReactiveFormsModule } from &#39;@angular/forms&#39;;
import { NzTableModule } from &#39;ng-zorro-antd/table&#39;;
import { NzModalModule } from &#39;ng-zorro-antd/modal&#39;;
import { NzButtonModule } from &#39;ng-zorro-antd/button&#39;;
import { NzFormModule } from &#39;ng-zorro-antd/form&#39;;
import { NzInputModule } from &#39;ng-zorro-antd/input&#39;;
// ...
imports: [ // 是在 imports 中添加,而不是 declarations 中声明
NzTableModule,
NzModalModule,
NzButtonModule,
NzFormModule,
ReactiveFormsModule,
NzInputModule
],</pre>
Simple and easy to understand principle, we do not use
here for nesting of routes: <pre class='brush:php;toolbar:false;'>// app.routing.module.ts
import { NgModule } from &#39;@angular/core&#39;;
import { Routes, RouterModule, PreloadAllModules } from &#39;@angular/router&#39;;
import { WelcomeComponent } from &#39;./pages/welcome/welcome.component&#39;;
import { UserComponent } from &#39;./pages/user/user.component&#39;;
import { UserInfoComponent } from &#39;./pages/user/user-info/user-info.component&#39;;
// 相关的路由
const routes: Routes = [
{
path: &#39;&#39;,
pathMatch: &#39;full&#39;,
redirectTo: &#39;/welcome&#39;
},
{
path: &#39;welcome&#39;,
component: WelcomeComponent
},
{
path: &#39;user&#39;,
component: UserComponent
},
{
path: &#39;user/add&#39;,
component: UserInfoComponent
},
{
path: &#39;user/edit/:uuid&#39;,
component: UserInfoComponent
}
];
@NgModule({
imports: [RouterModule.forRoot(
routes,
{
useHash: true,// 使用 hash 模式
preloadingStrategy: PreloadAllModules
}
)],
exports: [RouterModule]
})
export class AppRoutingModule { }</pre>
Change the menuThe menu generated using scaffolding does not match the functions we need to develop, let’s adjust it.
// app.component.html <nz-layout class="app-layout"> <nz-sider class="menu-sidebar" nzCollapsible nzWidth="256px" nzBreakpoint="md" [(nzCollapsed)]="isCollapsed" [nzTrigger]="null"> <div class="sidebar-logo"> <!-- 默认点击 logo 跳转到首页 --> <a routerLink="/welcome"> <img src="/static/imghwm/default1.png" data-src="https://ng.ant.design/assets/img/logo.svg" class="lazy" alt="logo"> <h1 id="Ng-Zorro">Ng-Zorro</h1> </a> </div> <ul nz-menu nzTheme="dark" nzMode="inline" [nzInlineCollapsed]="isCollapsed"> <li nz-submenu nzOpen nzTitle="用户管理" nzIcon="dashboard"> <ul> <li nz-menu-item nzMatchRouter> <a routerLink="/user">用户列表</a> </li> </ul> </li> </ul> </nz-sider> <nz-layout> <nz-header> <div class="app-header"> <span class="header-trigger" (click)="isCollapsed = !isCollapsed"> <i class="trigger" nz-icon [nzType]="isCollapsed ? 'menu-unfold' : 'menu-fold'" ></i> </span> </div> </nz-header> <nz-content> <div class="inner-content"> <router-outlet></router-outlet> </div> </nz-content> </nz-layout> </nz-layout>Menu display, if we need to do permission management, we need the backend to cooperate with the value transfer, and then we will render the relevant permission menu to the page
After replacing the above code, the basic skeleton obtained is as follows:
Complete user list Next, complete the skeleton of the user list. Because we use the
UI framework, it is extremely convenient for us to write:
// user.component.html
<nz-table #basicTable [nzData]="list">
<thead>
<tr>
<th>Name</th>
<th>Position</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<!-- 对获取到的数据进行遍历 -->
<tr *ngFor="let data of basicTable.data">
<td>{{data.name}}</td>
<td>{{data.position}}</td>
<td>
<a style="color: #f00;">Delete</a>
</td>
</tr>
</tbody>
</nz-table>
We simulated some data in the
folder user.json
:<pre class='brush:php;toolbar:false;'>{
"users": [
{
"uuid": 1,
"name": "Jimmy",
"position": "Frontend"
},
{
"uuid": 2,
"name": "Jim",
"position": "Backend"
}
],
"environment": "development"
}</pre>
After writing the service, we called to get the user's data:
// user.component.ts import { Component, OnInit } from '@angular/core'; import { UserService } from 'src/app/services/user.service'; @Component({ selector: 'app-user', templateUrl: './user.component.html', styleUrls: ['./user.component.scss'] }) export class UserComponent implements OnInit { public list: any = [] constructor( private readonly userService: UserService ) { } ngOnInit(): void { if(localStorage.getItem('users')) { let obj = localStorage.getItem('users') || '{}' this.list = JSON.parse(obj) } else { this.getList() } } // 获取用户列表 getList() { this.userService.getUserList().subscribe({ next: (data: any) => { localStorage.setItem('users', JSON.stringify(data.users)) this.list = data.users }, error: (error: any) => { console.log(error) } }) } }
Because no back-end service is introduced, here we use
localstorage to record the status. After completing the above, we get the list information as follows:
us Simply create a form, which contains only two fields, namely
name and position
. These two functions share a common form~We add in
:<pre class='brush:php;toolbar:false;'>// user-info.component.html
<form nz-form [formGroup]="validateForm" class="login-form" (ngSubmit)="submitForm()">
<nz-form-item>
<nz-form-control nzErrorTip="请输入用户名!">
<input type="text" nz-input formControlName="username" placeholder="请输入用户名" style="width: 160px;" />
</nz-form-control>
</nz-form-item>
<nz-form-item>
<nz-form-control nzErrorTip="请输入职位!">
<input type="text" nz-input formControlName="position" placeholder="请输入职位" style="width: 160px;"/>
</nz-form-control>
</nz-form-item>
<button nz-button class="login-form-button login-form-margin" [nzType]="&#39;primary&#39;">确认</button>
</form></pre>
The page looks like this:
然后就是逻辑的判断,进行添加或者是修改。如果是连接带上 uuid
的标识,就表示是编辑,show you the codes
。
// user-info.component.ts import { Component, OnInit } from '@angular/core'; import { FormBuilder, FormGroup, Validators } from '@angular/forms'; import { ActivatedRoute, ParamMap } from '@angular/router'; @Component({ selector: 'app-user-info', templateUrl: './user-info.component.html', styleUrls: ['./user-info.component.scss'] }) export class UserInfoComponent implements OnInit { public isAdd: boolean = true; public userInfo: any = [] public uuid: number = 0; validateForm!: FormGroup; constructor( private fb: FormBuilder, private route: ActivatedRoute, ) { } ngOnInit(): void { this.userInfo = JSON.parse(localStorage.getItem('users') || '[]') this.route.paramMap.subscribe((params: ParamMap)=>{ this.uuid = parseInt(params.get('uuid') || '0') }) // 是编辑状态,设置标志符 if(this.uuid) { this.isAdd = false } if(this.isAdd) { this.validateForm = this.fb.group({ username: [null, [Validators.required]], position: [null, [Validators.required]] }); } else { let current = (this.userInfo.filter((item: any) => item.uuid === this.uuid))[0] || {} // 信息回填 this.validateForm = this.fb.group({ username: [current.name, [Validators.required]], position: [current.position, [Validators.required]] }) } } submitForm() { // 如果不符合提交,则报错 if(!this.validateForm.valid) { Object.values(this.validateForm.controls).forEach((control: any) => { if(control?.invalid) { control?.markAsDirty(); control?.updateValueAndValidity({ onlySelf: true }); } }) return } // 获取到表单的数据 const data = this.validateForm.value // 新增用户 if(this.isAdd) { let lastOne = (this.userInfo.length > 0 ? this.userInfo[this.userInfo.length-1] : {}); this.userInfo.push({ uuid: (lastOne.uuid ? (lastOne.uuid + 1) : 1), name: data.username, position: data.position }) localStorage.setItem('users', JSON.stringify(this.userInfo)) } else { // 编辑用户,更新信息 let mapList = this.userInfo.map((item: any) => { if(item.uuid === this.uuid) { return { uuid: this.uuid, name: data.username, position: data.position } } return item }) localStorage.setItem('users', JSON.stringify(mapList)) } } }
我们先设定一个标志符 isAdd
,默认是新建用户;当 uuid
存在的时候,将其设置为 false
值,表示是编辑的状态,对内容进行表单的回填。提交表单的操作也是按照该标志符进行判断。我们直接对 localStorage
的信息进行变更,以保证同步列表信息。
删除功能
我们引入模态对话框进行询问是否删除。
// user.component.ts // 删除 delete(data: any) { this.modal.confirm({ nzTitle: '<i>你想删除该用户?</i>', nzOnOk: () => { let users = JSON.parse(localStorage.getItem('users') || '[]'); let filterList = users.filter((item: any) => item.uuid !== data.uuid); localStorage.setItem('users', JSON.stringify(filterList)); this.list = filterList } }); }
我们找到删除的数据,将其剔除,重新缓存新的用户数据,并更新 table
的用户列表数据。
So,到此为止,我们顺利完成了一个简单的项目。我们用 Gif
图整体来看看。
【完】
更多编程相关知识,请访问:编程入门!!
The above is the detailed content of Angular + NG-ZORRO quickly develop a backend system. For more information, please follow other related articles on the PHP Chinese website!

JavaandJavaScriptaredistinctlanguages:Javaisusedforenterpriseandmobileapps,whileJavaScriptisforinteractivewebpages.1)Javaiscompiled,staticallytyped,andrunsonJVM.2)JavaScriptisinterpreted,dynamicallytyped,andrunsinbrowsersorNode.js.3)JavausesOOPwithcl

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 Mac version
God-level code editing software (SublimeText3)

SublimeText3 Linux new version
SublimeText3 Linux latest version

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software
