目錄
Ng-Zorro
首頁 web前端 js教程 Angular + NG-ZORRO快速開發一個後台系統

Angular + NG-ZORRO快速開發一個後台系統

Apr 21, 2022 am 10:45 AM
angular

這篇文章跟大家分享一個Angular實戰,了解一下angualr 結合 ng-zorro 如何快速開發一個後台系統,希望對大家有所幫助!

Angular + NG-ZORRO快速開發一個後台系統

連更的這幾天的文章,我們已經了解了不少 angular 的知識點了,這次我們來個小成品。

angualr 結合 ng-zorro 快速且規範的開發一個後台系統。 【相關教學推薦:《angular教學》】

系統功能包含以下的內容:

  • 歡迎頁面
  • 使用者清單
  • 用戶新增
  • 用戶修改
  • 用戶刪除

所有的service 使用模擬的資料。

說乾咱就乾。

結合ng-zorro

#angular 比較流行的ui 框架有:

  • Angular Material 官方指定UI 框架
  • NG-ZORRO,又稱為Ant Design of Angular 國內較受歡迎的UI 框架

Ant Design 相信做前端開發的人兒都比較熟悉了。所以這裡我們結合 NG-ZORRO 這個框架來做。如果熟悉VueReact 版本的Ant Design,相信你可以無縫連結啊~

Angular + NG-ZORRO快速開發一個後台系統

# #我們重新使用

angular-cli 產生一個專案ng-zorro

新增

ng-zorro 是很簡單的事情:進入ng-zorro 根目錄,執行ng add ng-zorro-antd 即可。

當然你也可以執行

npm install ng-zorro-antd 添加,不建議。

結合

ng-zorro 完成之後,我們執行專案起來npm run start,你會在http://localhost:4200 的頁面看到下圖內容。

Angular + NG-ZORRO快速開發一個後台系統

Not Bad, Bro.

#設定路由

我們改成

hash 路由,並且加入使用者路由,鷹架都幫我們完事了,我們只要做點小修改。

想法:

  • 先加入頁面

    user 使用者的清單頁面,使用ng-zorrotable 元件

  • 使用者的新增與變更頁面可以共用同一個頁面,使用

    ng-zorroform 元件

  • 頁面刪除功能直接使用彈出式提示,使用

    ng-zorromodal 元件

ng-zorro 元件按需引入

調整路由檔案

依照思路,我們得在

ng-zorro
引入:

// app.module.ts

import { 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: [ // 是在 imports 中添加,而不是 declarations 中声明
  NzTableModule,
  NzModalModule,
  NzButtonModule,
  NzFormModule,
  ReactiveFormsModule,
  NzInputModule
],
登入後複製

簡單易理解原則,我們這裡不使用

childrenAngular + NG-ZORRO快速開發一個後台系統 進行路由的嵌套:

// app.routing.module.ts

import { 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';

// 相关的路由
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,// 使用 hash 模式
      preloadingStrategy: PreloadAllModules
    }
  )],
  exports: [RouterModule]
})
export class AppRoutingModule { }
登入後複製

#更改選單

使用腳手架產生的選單與我們需要開發的功能不符合,我們來調整下。 <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class='brush:php;toolbar:false;'>// app.component.html &lt;nz-layout class=&quot;app-layout&quot;&gt; &lt;nz-sider class=&quot;menu-sidebar&quot; nzCollapsible nzWidth=&quot;256px&quot; nzBreakpoint=&quot;md&quot; [(nzCollapsed)]=&quot;isCollapsed&quot; [nzTrigger]=&quot;null&quot;&gt; &lt;div class=&quot;sidebar-logo&quot;&gt; &lt;!-- 默认点击 logo 跳转到首页 --&gt; &lt;a routerLink=&quot;/welcome&quot;&gt; &lt;img src=&quot;/static/imghw/default1.png&quot; data-src=&quot;https://ng.ant.design/assets/img/logo.svg&quot; class=&quot;lazy&quot; alt=&quot;logo&quot;&gt; &lt;h1 id=&quot;Ng-Zorro&quot;&gt;Ng-Zorro&lt;/h1&gt; &lt;/a&gt; &lt;/div&gt; &lt;ul nz-menu nzTheme=&quot;dark&quot; nzMode=&quot;inline&quot; [nzInlineCollapsed]=&quot;isCollapsed&quot;&gt; &lt;li nz-submenu nzOpen nzTitle=&quot;用户管理&quot; nzIcon=&quot;dashboard&quot;&gt; &lt;ul&gt; &lt;li nz-menu-item nzMatchRouter&gt; &lt;a routerLink=&quot;/user&quot;&gt;用户列表&lt;/a&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/nz-sider&gt; &lt;nz-layout&gt; &lt;nz-header&gt; &lt;div class=&quot;app-header&quot;&gt; &lt;span class=&quot;header-trigger&quot; (click)=&quot;isCollapsed = !isCollapsed&quot;&gt; &lt;i class=&quot;trigger&quot; nz-icon [nzType]=&quot;isCollapsed ? &amp;#39;menu-unfold&amp;#39; : &amp;#39;menu-fold&amp;#39;&quot; &gt;&lt;/i&gt; &lt;/span&gt; &lt;/div&gt; &lt;/nz-header&gt; &lt;nz-content&gt; &lt;div class=&quot;inner-content&quot;&gt; &lt;router-outlet&gt;&lt;/router-outlet&gt; &lt;/div&gt; &lt;/nz-content&gt; &lt;/nz-layout&gt; &lt;/nz-layout&gt;</pre><div class="contentsignin">登入後複製</div></div>

選單展示,如果我們需要做權限管理的話,是需要後端配合進行傳值的,然後我們再把相關的權限選單渲染到頁面

替換成上面的程式碼後,得到的基本骨架如下:

#完成使用者清單

接下來完成使用者清單的骨架,因為使用了UI

框架,我麼寫起來異常的方便:

取得使用者清單Angular + NG-ZORRO快速開發一個後台系統##

// 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>
登入後複製

我們模擬了一些資料在

assets 資料夾中user.json

:

{
  "users": [
    {
      "uuid": 1,
      "name": "Jimmy",
      "position": "Frontend"
    },
    {
      "uuid": 2,
      "name": "Jim",
      "position": "Backend"
    }
  ],
  "environment": "development"
}
登入後複製
編寫好服務之後,我們呼叫取得使用者的資料:
// 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)
      }
    })
  }

}
登入後複製
因為沒有引入後端服務,這裡我們採用localstorage

的方式記錄狀態。

上面完成後,我們得到清單資訊如下:

Angular + NG-ZORRO快速開發一個後台系統#新增使用者和編輯使用者

#####我們簡單建立個表單,裡面含有的欄位就兩個,分別是###name### 和###position###。這兩個功能是公用一個表單的~######我們在###html### 中加入:###
// 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>
登入後複製
###頁長這樣子:########## ##

然后就是逻辑的判断,进行添加或者是修改。如果是连接带上 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快速開發一個後台系統

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

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

Angular + NG-ZORRO快速開發一個後台系統

【完】

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

以上是Angular + NG-ZORRO快速開發一個後台系統的詳細內容。更多資訊請關注PHP中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

熱門話題

Java教學
1657
14
CakePHP 教程
1415
52
Laravel 教程
1309
25
PHP教程
1257
29
C# 教程
1231
24
聊聊Angular中的元資料(Metadata)和裝飾器(Decorator) 聊聊Angular中的元資料(Metadata)和裝飾器(Decorator) Feb 28, 2022 am 11:10 AM

這篇文章繼續Angular的學習,帶大家了解Angular中的元數據和裝飾器,簡單了解一下他們的用法,希望對大家有幫助!

如何在Ubuntu 24.04上安裝Angular 如何在Ubuntu 24.04上安裝Angular Mar 23, 2024 pm 12:20 PM

Angular.js是一種可自由存取的JavaScript平台,用於建立動態應用程式。它允許您透過擴展HTML的語法作為模板語言,以快速、清晰地表示應用程式的各個方面。 Angular.js提供了一系列工具,可協助您編寫、更新和測試程式碼。此外,它還提供了許多功能,如路由和表單管理。本指南將討論在Ubuntu24上安裝Angular的方法。首先,您需要安裝Node.js。 Node.js是一個基於ChromeV8引擎的JavaScript運行環境,可讓您在伺服器端執行JavaScript程式碼。要在Ub

一文探究Angular中的服務端渲染(SSR) 一文探究Angular中的服務端渲染(SSR) Dec 27, 2022 pm 07:24 PM

你知道 Angular Universal 嗎?可以幫助網站提供更好的 SEO 支援哦!

angular學習之詳解狀態管理器NgRx angular學習之詳解狀態管理器NgRx May 25, 2022 am 11:01 AM

這篇文章帶大家深入了解angular的狀態管理器NgRx,介紹一下NgRx的使用方法,希望對大家有幫助!

Angular + NG-ZORRO快速開發一個後台系統 Angular + NG-ZORRO快速開發一個後台系統 Apr 21, 2022 am 10:45 AM

這篇文章跟大家分享一個Angular實戰,了解一下angualr 結合 ng-zorro 如何快速開發一個後台系統,希望對大家有幫助!

淺析angular中怎麼使用monaco-editor 淺析angular中怎麼使用monaco-editor Oct 17, 2022 pm 08:04 PM

angular中怎麼使用monaco-editor?以下這篇文章記錄下最近的一次業務中用到的 m​​onaco-editor 在 angular 中的使用,希望對大家有幫助!

如何使用PHP和Angular進行前端開發 如何使用PHP和Angular進行前端開發 May 11, 2023 pm 04:04 PM

隨著網路的快速發展,前端開發技術也不斷改進與迭代。 PHP和Angular是兩種廣泛應用於前端開發的技術。 PHP是一種伺服器端腳本語言,可以處理表單、產生動態頁面和管理存取權限等任務。而Angular是一種JavaScript的框架,可以用來開發單一頁面應用程式和建構元件化的網頁應用程式。本篇文章將介紹如何使用PHP和Angular進行前端開發,以及如何將它們

使用Angular和Node進行基於令牌的身份驗證 使用Angular和Node進行基於令牌的身份驗證 Sep 01, 2023 pm 02:01 PM

身份驗證是任何網路應用程式中最重要的部分之一。本教程討論基於令牌的身份驗證系統以及它們與傳統登入系統的差異。在本教程結束時,您將看到一個用Angular和Node.js編寫的完整工作演示。傳統身份驗證系統在繼續基於令牌的身份驗證系統之前,讓我們先來看看傳統的身份驗證系統。使用者在登入表單中提供使用者名稱和密碼,然後點擊登入。發出請求後,透過查詢資料庫在後端驗證使用者。如果請求有效,則使用從資料庫中獲取的使用者資訊建立會話,然後在回應頭中傳回會話訊息,以便將會話ID儲存在瀏覽器中。提供用於存取應用程式中受

See all articles