Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to develop a background system with Angular+NG-ZORRO

2025-02-23 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)05/31 Report--

Today, the editor will share with you the relevant knowledge points about how Angular+NG-ZORRO develops a background system. The content is detailed and the logic is clear. I believe most people still know too much about this knowledge, so share this article for your reference. I hope you can get something after reading this article. Let's take a look at it.

System functions include the following:

Welcome page

User list

User add

User modification

User deletion

All service uses simulated data.

If you say so, let's do it.

Combined with ng-zorro

The popular ui frameworks of angular are:

Angular Material officially designated UI framework

NG-ZORRO, also known as Ant Design of Angular, a popular UI framework in China.

Ant Design believes that people who do front-end developers are familiar with it. So here we combine the framework of NG-ZORRO to do it. If you are familiar with Vue or React version of Ant Design, I believe you can link seamlessly.

We re-use angular-cli to generate a project ng-zorro.

Adding ng-zorro is a simple thing: go to the ng-zorro root directory and execute ng add ng-zorro-antd.

Of course, you can also add npm install ng-zorro-antd, which is not recommended.

After the combination of ng-zorro is complete, we run the project npm run start, and you will see the following figure on the http://localhost:4200 page.

Not Bad, Bro.

Configure routin

We changed to hash routing, and added user routing, scaffolding to help us finish, we just need to make a little modification.

Train of thought:

Add a list page of user users first, and use the table component in ng-zorro

Users' new and changed pages can share the same page, using the form component in ng-zorro

The page deletion function directly uses the pop-up window prompt and uses the modal component in ng-zorro

Introduce ng-zorro components on demand

Adjust routing Fil

According to the idea, we have to introduce in ng-zorro:

/ / app.module.tsimport {ReactiveFormsModule} from'@ angular/forms';import {NzTableModule} from 'ng-zorro-antd/table';import {NzModalModule} from' ng-zorro-antd/modal';import {NzButtonModule} from 'ng-zorro-antd/button';import {NzFormModule} from' ng-zorro-antd/form';import {NzInputModule} from 'ng-zorro-antd/input' / /... imports: [/ / it is added to imports instead of declaring NzTableModule, NzModalModule, NzButtonModule, NzFormModule, ReactiveFormsModule, NzInputModule in declarations]

Easy to understand principle, we do not use children for routing nesting:

/ / app.routing.module.tsimport {NgModule} from'@ angular/core';import {Routes, RouterModule, PreloadAllModules} from'@ angular/router';import {WelcomeComponent} from'. / pages/welcome/welcome.component';import {UserComponent} from'. / pages/user/user.component';import {UserInfoComponent} from'. / pages/user/user-info/user-info.component' / / related routes const routes: Routes = [{path:', pathMatch: 'full', redirectTo:' / welcome'}, {path: 'welcome', component: WelcomeComponent}, {path:' user', component: UserComponent}, {path: 'user/add', component: UserInfoComponent}, {path:' user/edit/:uuid', component: UserInfoComponent}] @ NgModule ({imports: [RouterModule.forRoot (routes, {useHash: true,// uses hash mode preloadingStrategy: PreloadAllModules})], exports: [RouterModule]}) export class AppRoutingModule {}

Change menu

The menu generated by using scaffolding does not match the function we need to develop, so let's adjust it.

/ / app.component.html

logo

Ng-Zorro user list

The menu shows that if we need to do permission management, we need the cooperation of the back end to pass values, and then we render the relevant permissions menu to the page.

After replacing it with the above code, the basic skeleton is as follows:

Complete the user list

Next, complete the skeleton of the user list. Because of the use of the UI framework, it is extremely convenient for us to write:

Get user list

/ / user.component.html Name Position Action {{data.name}} {{data.position}} Delete

We simulated some data to user.json in the assets folder:

{"users": [{"uuid": 1, "name": "Jimmy", "position": "Frontend"}, {"uuid": 2, "name": "Jim", "position": "Backend"}], "environment": "development"}

After writing the service, we call to get the user's data:

/ / user.component.tsimport {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 ()}} / / get the user list 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)}})}}

Since no back-end service has been introduced, we use localstorage to record the status here.

After completing the above, we get the following list of information:

New and editing users

Let's simply create a form that contains only two fields, name and position. These two functions share a form.

We added the following to html:

/ / user-info.component.html confirmation

The page looks like this:

Then there is logical judgment, adding or modifying. If it is a connection with the uuid logo, it means it is an editor, show you the codes.

/ / user-info.component.tsimport {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; validateFormless: 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')}) / / is edited Set the marker 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] | | {} / / Information backfill this.validateForm = this.fb.group ({username: [current.name, [Validators.required]], position: [current.position [Validators.required]]})} submitForm () {/ / if the submission is not met If (! this.validateForm.valid) {Object.values (this.validateForm.controls) .forEach ((control: any) = > {if (control?.invalid) {control?.markAsDirty () Control?.updateValueAndValidity ({onlySelf: true});}}) return} / / get the data from the form const data = this.validateForm.value / / new user if (this.isAdd) {let lastOne = (this.userInfo.length > 0? This.userInfo.push [this.userInfo.length-1]: {}); this.userInfo.push ({userInfo: (lastOne.uuid?) (lastOne.uuid + 1): 1), name: data.username, position: data.position}) localStorage.setItem ('users', JSON.stringify (this.userInfo))} else {/ / Edit user Update information 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))}

We first set a marker isAdd, which is the new user by default; when uuid exists, set it to the value of false, which indicates that it is the state of editing, and backfill the content of the form. The operation of submitting the form is also judged by this marker. We make changes to the localStorage information directly to ensure that the list information is synchronized.

Delete function

We introduce a modal dialog box to ask whether to delete or not.

/ / user.component.ts// delete delete (data: any) {this.modal.confirm ({nzTitle:'do you want to delete the user?', 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});}

We find the deleted data, weed it out, re-cache the new user data, and update table's user list data.

These are all the contents of the article "how to develop a background system in Angular+NG-ZORRO". Thank you for reading! I believe you will gain a lot after reading this article. The editor will update different knowledge for you every day. If you want to learn more knowledge, please pay attention to the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report