angular环境已安装,版本信息如下:
Angular Cl: 16.2.0
node: 18.10.0
Package Manager: npm 8.19.2
OS:win32 x64
1.使用angular cli创建一个项目
2.设计一个登录界面,包含用户名密码登录进系统,有两个功能菜单, 用户管理和角色管理, 用户信息包含必输信息:账号,姓名,密码,角色,激活状态,可选:【邮箱,手机号】等信息 角色管理 角色信息包含角色名称以及功能权限(可以操作的功能清单 )
以上生成完整的代码,以及给出详细的代码文件结构说明
你目前的 Angular 环境(CLI 16 + Node 18)完全足以构建一个中小型后台管理系统。
我将一步步帮你完成以下内容:
🧩 目标
✅ 使用 Angular CLI 创建一个完整的项目
✅ 实现登录功能(用户名 + 密码)
✅ 登录后进入主界面,包含两个菜单页:
用户管理(CRUD)
角色管理(包含权限配置)
✅ 输出:
完整项目结构(文件树 + 每层说明)
全部关键代码(可直接运行)
🚀 第一步:创建 Angular 项目
ng new admin-system --routing --style=scss
cd admin-system
ng serve
这将创建一个带路由支持的项目,并启动在 http://localhost:4200。
📁 第二步:项目结构规划
创建后的目录结构调整为:
admin-system/
├── src/
│ ├── app/
│ │ ├── core/ # 核心服务/守卫/接口
│ │ │ ├── auth/
│ │ │ │ ├── auth.service.ts # 登录逻辑(假接口)
│ │ │ │ ├── auth.guard.ts # 路由守卫
│ │ │ └── models/
│ │ │ ├── user.model.ts # 用户数据模型
│ │ │ └── role.model.ts # 角色数据模型
│ │ ├── layout/
│ │ │ ├── layout.component.ts # 布局(顶部菜单 + 左侧菜单)
│ │ │ ├── layout.component.html
│ │ │ └── layout.component.scss
│ │ ├── login/
│ │ │ ├── login.component.ts # 登录界面
│ │ │ ├── login.component.html
│ │ │ └── login.component.scss
│ │ ├── user-management/
│ │ │ ├── user-list.component.ts
│ │ │ ├── user-list.component.html
│ │ │ ├── user-edit.component.ts
│ │ │ ├── user-edit.component.html
│ │ │ └── user.service.ts
│ │ ├── role-management/
│ │ │ ├── role-list.component.ts
│ │ │ ├── role-list.component.html
│ │ │ ├── role-edit.component.ts
│ │ │ ├── role-edit.component.html
│ │ │ └── role.service.ts
│ │ ├── app-routing.module.ts
│ │ ├── app.component.ts
│ │ ├── app.component.html
│ │ └── app.module.ts
│ └── assets/
│ └── mock-data/ # 假数据
│ ├── users.json
│ └── roles.json
├── angular.json
├── package.json
└── tsconfig.json
🧠 第三步:路由配置(app-routing.module.ts)
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { LoginComponent } from './login/login.component';
import { LayoutComponent } from './layout/layout.component';
import { AuthGuard } from './core/auth/auth.guard';const routes: Routes = [{ path: 'login', component: LoginComponent },{path: '',component: LayoutComponent,canActivate: [AuthGuard],children: [{ path: 'users', loadChildren: () => import('./user-management/user.module').then(m => m.UserModule) },{ path: 'roles', loadChildren: () => import('./role-management/role.module').then(m => m.RoleModule) },{ path: '', redirectTo: '/users', pathMatch: 'full' },],},{ path: '**', redirectTo: '/login' },
];@NgModule({imports: [RouterModule.forRoot(routes)],exports: [RouterModule],
})
export class AppRoutingModule {}
🧾 第四步:登录模块
login.component.html
<div class="login-container"><h2>系统登录</h2><form (ngSubmit)="login()" #form="ngForm"><input type="text" name="username" [(ngModel)]="username" placeholder="用户名" required /><input type="password" name="password" [(ngModel)]="password" placeholder="密码" required /><button type="submit" [disabled]="form.invalid">登录</button><p class="error" *ngIf="errorMsg">{{ errorMsg }}</p></form>
</div>
login.component.ts
import { Component } from '@angular/core';
import { Router } from '@angular/router';
import { AuthService } from '../core/auth/auth.service';@Component({selector: 'app-login',templateUrl: './login.component.html',styleUrls: ['./login.component.scss'],
})
export class LoginComponent {username = '';password = '';errorMsg = '';constructor(private authService: AuthService, private router: Router) {}login() {if (this.authService.login(this.username, this.password)) {this.router.navigate(['/']);} else {this.errorMsg = '用户名或密码错误';}}
}
auth.service.ts
import { Injectable } from '@angular/core';@Injectable({ providedIn: 'root' })
export class AuthService {private isLoggedIn = false;login(username: string, password: string): boolean {if (username === 'admin' && password === '123456') {this.isLoggedIn = true;localStorage.setItem('token', 'fake-jwt-token');return true;}return false;}logout() {this.isLoggedIn = false;localStorage.removeItem('token');}checkLogin(): boolean {return !!localStorage.getItem('token');}
}
auth.guard.ts
import { Injectable } from '@angular/core';
import { CanActivate, Router } from '@angular/router';
import { AuthService } from './auth.service';@Injectable({ providedIn: 'root' })
export class AuthGuard implements CanActivate {constructor(private auth: AuthService, private router: Router) {}canActivate(): boolean {if (this.auth.checkLogin()) return true;this.router.navigate(['/login']);return false;}
}
🧭 第五步:主布局页面(Layout)
layout.component.html
<div class="layout"><aside><ul><li><a routerLink="/users">用户管理</a></li><li><a routerLink="/roles">角色管理</a></li><li (click)="logout()">退出登录</li></ul></aside><main><router-outlet></router-outlet></main>
</div>
layout.component.ts
import { Component } from '@angular/core';
import { Router } from '@angular/router';
import { AuthService } from '../core/auth/auth.service';@Component({selector: 'app-layout',templateUrl: './layout.component.html',styleUrls: ['./layout.component.scss'],
})
export class LayoutComponent {constructor(private auth: AuthService, private router: Router) {}logout() {this.auth.logout();this.router.navigate(['/login']);}
}
👥 第六步:用户管理模块
user.model.ts
export interface User {id: number;account: string;name: string;password: string;role: string;active: boolean;email?: string;phone?: string;
}
user-list.component.html
<h3>用户管理</h3>
<table><tr><th>账号</th><th>姓名</th><th>角色</th><th>激活状态</th><th>操作</th></tr><tr *ngFor="let user of users"><td>{{ user.account }}</td><td>{{ user.name }}</td><td>{{ user.role }}</td><td>{{ user.active ? '启用' : '禁用' }}</td><td><button (click)="editUser(user)">编辑</button></td></tr>
</table>
user.service.ts
import { Injectable } from '@angular/core';
import { User } from '../core/models/user.model';@Injectable({ providedIn: 'root' })
export class UserService {private users: User[] = [{ id: 1, account: 'admin', name: '管理员', password: '123456', role: '系统管理员', active: true },{ id: 2, account: 'test', name: '测试员', password: '123456', role: '普通用户', active: false },];getUsers() {return this.users;}
}
🔐 第七步:角色管理模块
role.model.ts
export interface Role {id: number;name: string;permissions: string[];
}
role-list.component.html
<h3>角色管理</h3>
<table><tr><th>角色名称</th><th>权限清单</th></tr><tr *ngFor="let role of roles"><td>{{ role.name }}</td><td>{{ role.permissions.join(', ') }}</td></tr>
</table>
role.service.ts
import { Injectable } from '@angular/core';
import { Role } from '../core/models/role.model';@Injectable({ providedIn: 'root' })
export class RoleService {private roles: Role[] = [{ id: 1, name: '系统管理员', permissions: ['查看用户', '编辑用户', '删除用户'] },{ id: 2, name: '普通用户', permissions: ['查看用户'] },];getRoles() {return this.roles;}
}
💡 第八步:运行项目
ng serve
访问:http://localhost:4200
登录用户名:admin
密码:123456
✅ 最终效果
登录界面
左侧菜单:用户管理、角色管理
用户列表展示基本信息
角色页面展示权限清单
登录拦截 + 退出登录功能完整