
지난 며칠 동안 우리는 angular 에 대해 많은 것을 배웠습니다. 이번에는 작은 제품을 생각해 보겠습니다.
angualr 는 ng-zorro 와 결합되어 백엔드 시스템을 빠르고 표준화하여 개발합니다. [관련 튜토리얼 권장사항: "Angular Tutorial"]
시스템 기능에는 다음이 포함됩니다.
모든 서비스 삭제 시뮬레이션 데이터를 사용합니다.
해보자.
ng-zorro Angular와 결합되어
더 인기 있는 ui angular
프론트엔드 개발을 하시는 분들이 Ant Design . 그것에 익숙합니다. 그래서 여기서는 이를 NG-ZORRO 프레임워크와 결합합니다. Vue 나 React 버전의 Ant Design 에 익숙하신 분들이라면 원활하게 연결하실 수 있을 거라 믿습니다~

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 페이지에 다음 그림이 표시됩니다.

나쁘지 않습니다.
구성 라우팅을
hash 라우팅으로 변경하고 스캐폴딩을 통해 몇 가지만 수정하면 됩니다.
아이디어:
먼저 페이지 user 목록 페이지를 추가하고, ng-zorro 의 table 구성 요소를 사용하여
사용자 페이지를 추가 및 변경하여 동일한 페이지를 공유 form ng-zorro
ng-zorro의 양식 구성 요소 페이지 삭제 기능을 사용하여 팝업 프롬프트를 직접 사용합니다. , ng-zorro
라우팅 파일을 조정하기
위해 필요에 따라 ng-zorro 구성 요소를 도입합니다
아이디어에 따르면 ng-zorro 에 이를 도입해야 합니다.
// app.module.ts
import { ReactiveFormsModule } from '@angular/forms';
'ng-zorro-antd/table'에서 { NzTableModule }을 가져옵니다.
'ng-zorro-antd/modal'에서 { NzModalModule }을 가져옵니다.
import { NzButtonModule } from 'ng-zorro-antd/button';
'ng-zorro-antd/form'에서 { NzFormModule }을 가져옵니다.
import { NzInputModule } from 'ng-zorro-antd/input';
// ...
imports: [ // 선언에서 NzTableModule을 선언하는 대신 imports에 추가합니다.
NzModal모듈,
NzButton모듈,
NzForm모듈,
ReactiveForms모듈,
NzInput모듈
], 간단하고 이해하기 쉬운 원리, children 는 하위 라우팅을 중첩하는 데 사용하지 않습니다:
// app.routing.module.ts
'@angular/core'에서 { NgModule }을 가져옵니다.
import { Routes, RouterModule, PreloadAllModules } from '@angular/router';
import { WelcomeComponent } from './pages/welcome/welcome.comComponent';
'./pages/user/user.comComponent'에서 { UserComponent }를 가져옵니다.
'./pages/user/user-info/user-info.comComponent'에서 { UserInfoComponent }를 가져옵니다.
//관련 경로 const 경로: 경로 = [
{
길: '',
pathMatch: '전체',
리디렉션 대상: '/환영합니다'
},
{
경로: '환영합니다',
구성요소: WelcomeComponent
},
{
경로: '사용자',
구성 요소: 사용자 구성 요소
},
{
경로: '사용자/추가',
구성 요소: UserInfoComponent
},
{
경로: '사용자/편집/:uuid',
구성 요소: UserInfoComponent
}
];
@NgModule({
수입: [RouterModule.forRoot(
경로,
{
useHash: true,//해시 모드 사용 preloadingStrategy: PreloadAllModules
}
)],
내보내기: [RouterModule]
})
내보내기 클래스 AppRoutingModule { } 메뉴 변경
스캐폴딩을 사용하여 생성한 메뉴가 우리가 개발해야 할 기능과 일치하지 않습니다.
// app.comComponent.html
<nz-레이아웃 클래스="앱-레이아웃">
<nz-sider class="메뉴 사이드바"
nz접이식
nzWidth="256px"
nzBreakpoint="md"
[(nzCollapsed)]="접힘됨"
[nzTrigger]="null">
<div 클래스="사이드바-로고">
<!-- 기본적으로 로고를 클릭하면 홈페이지로 이동합니다 -->
<a routerLink="/환영">
<img src="https://ng.ant.design/assets/img/logo.svg" alt="로고">
<h1>응조로</h1>
</a>
</div>
<ul nz-menu nzTheme="dark" nzMode="inline" [nzInlineCollapsed]="isCollapsed">
<li nz-submenu nzOpen nzTitle="사용자 관리" nzIcon="대시보드">
<ul>
<li nz-메뉴-항목 nzMatchRouter>
<a routerLink="/user">사용자 목록</a>
</li>
</ul>
</li>
</ul>
</nz-사이더>
<nz-레이아웃>
<nz-헤더>
<div 클래스="앱 헤더">
<span class="header-trigger" (클릭)="isCollapsed = !isCollapsed">
<i 클래스="트리거"
nz-아이콘
[nzType]="isCollapsed ? '메뉴 펼치기' : '메뉴 접기'"
></i>
</span>
</div>
</nz-헤더>
<nz-내용>
<div 클래스="내부 콘텐츠">
<라우터 아웃렛></라우터 아웃렛>
</div>
</nz-내용>
</nz-레이아웃>
</nz-layout> 메뉴 표시, 권한 관리를 수행해야 하는 경우 값 전송에 협력하기 위한 백엔드가 필요합니다. 그런 다음 관련 권한 메뉴를 페이지에 렌더링하고
이를 위의 코드로 대체합니다. 다음과 같습니다:

사용자 목록 완성
다음으로 사용자 목록의 뼈대를 완성합니다. UI 프레임워크를 사용하므로 다음과 같이 작성하는 것이 매우 편리합니다.
사용자 목록 가져오기
// user.comComponent.html
<nz-테이블 #basicTable [nzData]="목록">
<머리>
<tr>
<th>이름</th>
<th>직위</th>
<th>액션</th>
</tr>
</thead>
<본체>
<!-- 획득한 데이터 탐색 -->
<tr *ngFor="basicTable.data의 데이터를 저장">
<td>{{데이터.이름}}</td>
<td>{{데이터.위치}}</td>
<TD>
<a style="color: #f00;">삭제</a>
</td>
</tr>
</tbody>
</nz-table> assets 폴더 user.json 의 일부 데이터를 시뮬레이션했습니다.
{
"사용자": [
{
"uuid": 1,
"이름": "지미",
"position": "프런트엔드"
},
{
"uuid": 2,
"이름": "짐",
"position": "백엔드"
}
],
"환경": "개발"
} 서비스를 작성한 후 사용자 데이터를 가져오기 위해 호출합니다.
// user.comComponent.ts
import { Component, OnInit } from '@angular/core';
'src/app/services/user.service'에서 { UserService }를 가져옵니다.
@요소({
선택기: '앱 사용자',
templateUrl: './user.comComponent.html',
styleUrls: ['./user.comComponent.scss']
})
내보내기 클래스 UserComponent는 OnInit {를 구현합니다.
공개 목록: 모두 = []
건설자(
개인 읽기 전용 userService: UserService
) { }
ngOnInit(): 무효 {
if(localStorage.getItem('사용자')) {
let obj = localStorage.getItem('users') ||
this.list = JSON.parse(obj)
} 또 다른 {
this.getList()
}
}
// 사용자 목록을 가져옵니다. getList() {
this.userService.getUserList().subscribe({
다음: (데이터: 임의) => {
localStorage.setItem('users', JSON.stringify(data.users))
this.list = 데이터.사용자
},
오류: (오류: 모두) => {
console.log(오류)
}
})
}
} 백엔드 서비스가 도입되지 않았기 때문에 여기서는 localstorage 사용하여 상태를 기록합니다.
위의 작업을 완료하면 다음과 같은 목록 정보를 얻습니다.

사용자를 추가하고 편집하려면
name 과 position 라는 두 개의 필드만 포함된 양식을 생성하기만 하면 됩니다. 이 두 함수는 양식을 공유합니다.
html 에 추가합니다.
// user-info.comComponent.html
<form nz-form [formGroup]="validateForm" class="login-form" (ngSubmit)="submitForm()">
<nz-양식 항목>
<nz-form-control nzErrorTip="사용자 이름을 입력하세요!">
<input type="text" nz-input formControlName="username" placeholder="사용자 이름을 입력하세요" style="width: 160px;"
</nz-양식-제어>
</nz-양식-항목>
<nz-양식 항목>
<nz-form-control nzErrorTip="직위를 입력하세요!">
<input type="text" nz-input formControlName="position" placeholder="위치를 입력하세요" style="width: 160px;"/>
</nz-양식-제어>
</nz-양식-항목>
<button nz-button class="login-form-button login-form-margin" [nzType]="'primary'">확인</button>
</form> 페이지는 다음과 같습니다.

그런 다음 추가하거나 수정하기 위한 논리적 판단이 있습니다. 연결이 uuid 로 표시되면 편집을 의미하며 show you the codes .
// user-info.comComponent.ts
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { ActivatedRoute, ParamMap } from '@angular/router';
@요소({
선택기: 'app-user-info',
templateUrl: './user-info.comComponent.html',
styleUrls: ['./user-info.comComponent.scss']
})
내보내기 클래스 UserInfoComponent는 OnInit {를 구현합니다.
공개 isAdd: 부울 = true;
공개 userInfo: 모두 = []
공개 uuid: 숫자 = 0;
verifyForm!: FormGroup;
건설자(
비공개 FB: FormBuilder,
개인 경로: ActivatedRoute,
) { }
ngOnInit(): 무효 {
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 = 거짓
}
if(this.isAdd) {
this.validateForm = this.fb.group({
사용자 이름: [null, [Validators.required]],
위치: [null, [Validators.required]]
});
} 또 다른 {
let current = (this.userInfo.filter((item: any) => item.uuid === this.uuid))[0] ||
// 정보 채우기 this.validateForm = this.fb.group({
사용자 이름: [현재.이름, [Validators.required]],
위치: [현재.위치, [Validators.required]]
})
}
}
제출양식() {
// 제출 내용을 준수하지 않는 경우 오류가 보고됩니다. if(!this.validateForm.valid) {
Object.values(this.validateForm.controls).forEach((control: any) => {
if(control?.invalid) {
제어?.markAsDirty();
control?.updateValueAndValidity({ onlySelf: true });
}
})
반품
}
// 양식 데이터 가져오기 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),
이름: 데이터.사용자 이름,
위치: 데이터.위치
})
localStorage.setItem('users', JSON.stringify(this.userInfo))
} else { //사용자 편집, 정보 업데이트 let mapList = this.userInfo.map((item: any) => {
if(item.uuid === this.uuid) {
반품 {
uuid: this.uuid,
이름: 데이터.사용자 이름,
위치: 데이터.위치
}
}
반품 상품
})
localStorage.setItem('users', JSON.stringify(mapList))
}
}
} 먼저 uuid 존재하는 경우 새 사용자로 기본 설정되는 식별자 isAdd 설정하고 이를 false 값으로 설정하여 편집 상태에 있음을 나타내고 콘텐츠로 양식을 채웁니다. 양식 제출 작업도 이 식별자에 따라 판단됩니다. 목록 정보의 동기화를 보장하기 위해 localStorage 정보를 직접 변경합니다.
삭제 기능의 경우
삭제 여부를 묻는 모달 대화 상자를 도입합니다.
// user.comComponent.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 = 필터리스트
}
});
} 
삭제된 데이터를 찾아서 제거하고, 새로운 사용자 데이터를 다시 캐시하고, table 의 사용자 목록 데이터를 업데이트합니다.
이로써 지금까지 간단한 프로젝트를 성공적으로 완료했습니다. Gif 이용하여 전체적으로 살펴보겠습니다.

【위에】