最近负责的Vue项目上线后,接手了Angular项目,程序猿真的好辛苦(已哭晕),Vue3.0也出来了,但是现还目前在公司,只能硬着头皮先学习Angular,接手的项目是一个管理平台,管理平台离不开CURD增删改查,那么就先从CURD开始练起,之前一直在用Vue开发项目,上手Angular了解语法后还是很快就掌握了 φ(* ̄0 ̄)
首先从安装cli开始:
//全局安装脚手架
npm install -g @angular/cli
//接着创建项目
ng new 项目名称
//运行项目
ng serve
//创建组件(例如在app下)
ng generate component 组件名称
打开创建组件的html,写入默认样式:
<div>姓名:<input type="text"></div>
<div>年龄:<input type="text"></div>
<div>电话:<input type="text"></div>
<button>提交</button>
<button>确认修改</button>
<table>
<thead>
<tr>
<th>姓名</th>
<th>年龄</th>
<th>电话</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td></td>
<td></td>
<td>
<a href="javascript:;">删除</a>
<a href="javascript:;">修改</a>
</td>
</tr>
</tbody>
</table>
在ts文件里定义一些变量:
list: Array<object> = []; //所有的数据
name: string;//姓名绑定的属性
age: string;//年龄绑定的属性
tel: string;//电话绑定的属性
flag: boolean = true;//提交和确认修改切换的状态
upIndex:number;//修改的索引
依此给元素绑定上:
<div>姓名:<input type="text" [(ngModel)]="name"></div>
<div>年龄:<input type="text" [(ngModel)]="age"></div>
<div>电话:<input type="text" [(ngModel)]="tel"></div>
<button [hidden]="!flag">提交</button>
<button [hidden]="flag">确认修改</button>
定义提交方法:
fn(){
//给list数组push页面中输入框的值
this.list.push({
name: this.name,
age: this.age,
tel: this.tel,
})
//添加完清除输入框的value
this.name = this.age = this.tel = ''
}
给元素绑定上:
<button [hidden]="!flag" (click)="fn()">提交</button>
遍历list数组:
<table>
<thead>
<tr>
<th>姓名</th>
<th>年龄</th>
<th>电话</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let item of list;let i = index">
<td>{{item.name}}</td>
<td>{{item.age}}</td>
<td>{{item.tel}}</td>
<td>
<a href="javascript:;">删除</a>
<a href="javascript:;">修改</a>
</td>
</tr>
</tbody>
</table>
删除时传入索引:
<a href="javascript:;" (click)="del(i)">删除</a>
定义删除方法:
del(i) {
this.list.splice(i, 1)
}
修改时传入这一项的数据和索引:
<a href="javascript:;" (click)="up(item,i)">修改</a>
定义修改方法:
up(item,i) {
//把当前项的数据赋值给相应的input框
this.name = item.name;
this.age = item.age;
this.tel = item.tel;
this.upIndex = i //索引赋值给变量upIndex
this.flag = false; //按钮状态为false
}
最后确认修改:
<button [hidden]="flag" (click)="update()">确认修改</button>
定义确认修改方法:
update(){
//按照索引修改
this.list[this.upIndex] = {
name: this.name,
age: this.age,
tel: this.tel,
}
this.flag = true //按钮状态为true
this.name = this.age = this.tel = '' //清空文本框的value
}
一套简单的CURD就完成了,仔细阅读注释 ε=ε=ε=( ̄▽ ̄)