search
HomeWeb Front-endJS TutorialAngular + NG-ZORRO quickly develop a backend system

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!

Angular + NG-ZORRO quickly develop a backend system

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 + NG-ZORRO quickly develop a backend system

We reuse

angular-cli to generate a project ng-zorro.

Adding

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 execute

npm install ng-zorro-antd to add, but it is not recommended.

Combined

ng-zorro After completion, we run the projectnpm run start, you will be inhttp://localhost:4200 page, see the content below.

Angular + NG-ZORRO quickly develop a backend system

Not Bad, Bro.

Configure routing

We changed it to

hash routing and added user routing. The scaffolding has done it for us, we only need to make some minor modifications.

Idea:

  • First add the page

    user User's list page, use ng-zorro in table Component

  • 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
ng-zorro

introduces: <pre class='brush:php;toolbar:false;'>// app.module.ts import { ReactiveFormsModule } from &amp;#39;@angular/forms&amp;#39;; import { NzTableModule } from &amp;#39;ng-zorro-antd/table&amp;#39;; import { NzModalModule } from &amp;#39;ng-zorro-antd/modal&amp;#39;; import { NzButtonModule } from &amp;#39;ng-zorro-antd/button&amp;#39;; import { NzFormModule } from &amp;#39;ng-zorro-antd/form&amp;#39;; import { NzInputModule } from &amp;#39;ng-zorro-antd/input&amp;#39;; // ... imports: [ // 是在 imports 中添加,而不是 declarations 中声明 NzTableModule, NzModalModule, NzButtonModule, NzFormModule, ReactiveFormsModule, NzInputModule ],</pre> Simple and easy to understand principle, we do not use

children

here for nesting of routes: <pre class='brush:php;toolbar:false;'>// app.routing.module.ts import { NgModule } from &amp;#39;@angular/core&amp;#39;; import { Routes, RouterModule, PreloadAllModules } from &amp;#39;@angular/router&amp;#39;; import { WelcomeComponent } from &amp;#39;./pages/welcome/welcome.component&amp;#39;; import { UserComponent } from &amp;#39;./pages/user/user.component&amp;#39;; import { UserInfoComponent } from &amp;#39;./pages/user/user-info/user-info.component&amp;#39;; // 相关的路由 const routes: Routes = [ { path: &amp;#39;&amp;#39;, pathMatch: &amp;#39;full&amp;#39;, redirectTo: &amp;#39;/welcome&amp;#39; }, { path: &amp;#39;welcome&amp;#39;, component: WelcomeComponent }, { path: &amp;#39;user&amp;#39;, component: UserComponent }, { path: &amp;#39;user/add&amp;#39;, component: UserInfoComponent }, { path: &amp;#39;user/edit/:uuid&amp;#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 ? &#39;menu-unfold&#39; : &#39;menu-fold&#39;"
            ></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:

Angular + NG-ZORRO quickly develop a backend system

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:

Get the user list

// 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

assets

folder user.json:<pre class='brush:php;toolbar:false;'>{ &quot;users&quot;: [ { &quot;uuid&quot;: 1, &quot;name&quot;: &quot;Jimmy&quot;, &quot;position&quot;: &quot;Frontend&quot; }, { &quot;uuid&quot;: 2, &quot;name&quot;: &quot;Jim&quot;, &quot;position&quot;: &quot;Backend&quot; } ], &quot;environment&quot;: &quot;development&quot; }</pre> After writing the service, we called to get the user's data:

// user.component.ts

import { Component, OnInit } from &#39;@angular/core&#39;;
import { UserService } from &#39;src/app/services/user.service&#39;;

@Component({
  selector: &#39;app-user&#39;,
  templateUrl: &#39;./user.component.html&#39;,
  styleUrls: [&#39;./user.component.scss&#39;]
})
export class UserComponent implements OnInit {

  public list: any = []

  constructor(
    private readonly userService: UserService
  ) { }

  ngOnInit(): void {
    if(localStorage.getItem(&#39;users&#39;)) {
      let obj = localStorage.getItem(&#39;users&#39;) || &#39;{}&#39;
      this.list =  JSON.parse(obj)
    } else {
      this.getList()
    }
  }

  // 获取用户列表
  getList() {
    this.userService.getUserList().subscribe({
      next: (data: any) => {
        localStorage.setItem(&#39;users&#39;, 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:

Angular + NG-ZORRO quickly develop a backend system

New users and edit users

us Simply create a form, which contains only two fields, namely

name

and position. These two functions share a common form~We add in

html

:<pre class='brush:php;toolbar:false;'>// user-info.component.html &lt;form nz-form [formGroup]=&quot;validateForm&quot; class=&quot;login-form&quot; (ngSubmit)=&quot;submitForm()&quot;&gt; &lt;nz-form-item&gt; &lt;nz-form-control nzErrorTip=&quot;请输入用户名!&quot;&gt; &lt;input type=&quot;text&quot; nz-input formControlName=&quot;username&quot; placeholder=&quot;请输入用户名&quot; style=&quot;width: 160px;&quot; /&gt; &lt;/nz-form-control&gt; &lt;/nz-form-item&gt; &lt;nz-form-item&gt; &lt;nz-form-control nzErrorTip=&quot;请输入职位!&quot;&gt; &lt;input type=&quot;text&quot; nz-input formControlName=&quot;position&quot; placeholder=&quot;请输入职位&quot; style=&quot;width: 160px;&quot;/&gt; &lt;/nz-form-control&gt; &lt;/nz-form-item&gt; &lt;button nz-button class=&quot;login-form-button login-form-margin&quot; [nzType]=&quot;&amp;#39;primary&amp;#39;&quot;&gt;确认&lt;/button&gt; &lt;/form&gt;</pre>The page looks like this:

然后就是逻辑的判断,进行添加或者是修改。如果是连接带上 uuid 的标识,就表示是编辑,show you the codes

// user-info.component.ts

import { Component, OnInit } from &#39;@angular/core&#39;;
import { FormBuilder, FormGroup, Validators } from &#39;@angular/forms&#39;;
import { ActivatedRoute, ParamMap } from &#39;@angular/router&#39;;

@Component({
  selector: &#39;app-user-info&#39;,
  templateUrl: &#39;./user-info.component.html&#39;,
  styleUrls: [&#39;./user-info.component.scss&#39;]
})
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(&#39;users&#39;) || &#39;[]&#39;)
    this.route.paramMap.subscribe((params: ParamMap)=>{
      this.uuid = parseInt(params.get(&#39;uuid&#39;) || &#39;0&#39;)
    })
    // 是编辑状态,设置标志符
    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(&#39;users&#39;, 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(&#39;users&#39;, JSON.stringify(mapList))
    }
  }

}

我们先设定一个标志符 isAdd,默认是新建用户;当 uuid 存在的时候,将其设置为 false 值,表示是编辑的状态,对内容进行表单的回填。提交表单的操作也是按照该标志符进行判断。我们直接对 localStorage 的信息进行变更,以保证同步列表信息。

删除功能

我们引入模态对话框进行询问是否删除。

// user.component.ts

// 删除
delete(data: any) {
  this.modal.confirm({
    nzTitle: &#39;<i>你想删除该用户?</i>&#39;,
    nzOnOk: () => {
      let users = JSON.parse(localStorage.getItem(&#39;users&#39;) || &#39;[]&#39;);
      let filterList = users.filter((item: any) => item.uuid !== data.uuid);
      localStorage.setItem(&#39;users&#39;, JSON.stringify(filterList));
      this.list = filterList
    }
  });
}

Angular + NG-ZORRO quickly develop a backend system

我们找到删除的数据,将其剔除,重新缓存新的用户数据,并更新 table 的用户列表数据。

So,到此为止,我们顺利完成了一个简单的项目。我们用 Gif 图整体来看看。

Angular + NG-ZORRO quickly develop a backend system

【完】

更多编程相关知识,请访问:编程入门!!

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!

Statement
This article is reproduced at:掘金社区. If there is any infringement, please contact admin@php.cn delete
Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The Evolution of JavaScript: Current Trends and Future ProspectsThe Evolution of JavaScript: Current Trends and Future ProspectsApr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Atom editor mac version download

Atom editor mac version download

The most popular open source editor