新建Form

模拟数据增删改查

在form的html中,追加三个输入框分别为:ID、姓名、年龄和4个按钮(查询、添加、更新、删除)。

1. form.component.html中添加输入框和按钮

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
// form.component.html
<style>
  div {
    margin-bottom: 10px;
  }

  button {
    margin-right: 10px;
  }
</style>

<!--ID-->
<div>
  <label>ID:</label>
  <input #id type="number" min="0">
</div>

<!--姓名-->
<div>
  <label>姓名:</label>
  <input #name type="text">
</div>

<!--年龄-->
<div>
  <label>年龄:</label>
  <input #age type="number" min="0">
</div>

<!--按钮-->
<button (click)="search()">查询</button>
<button (click)="add()">添加</button>
<button (click)="update()">更新</button>
<button (click)="delete()">删除</button>

2. app.component.ts中相应的事件

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
// form.compent.ts
/**
 * 利用ViewChild绑定html中<input #id type="number" min="0">的id
 */
 @ViewChild('id', {static: true})
 readonly id: ElementRef<HTMLInputElement>;
/**
 * 姓名
 */
@ViewChild('name', {static: true})
readonly name: ElementRef<HTMLInputElement>;
/**
 * 年龄
 */
@ViewChild('age', {static: true})
readonly age: ElementRef<HTMLInputElement>;

/**
 * 查找
 */
search() {
}

/**
 * 添加
 */
add() {
}

/**
 * 更新
 */
update() {
}

/**
 * 删除
 */
delete() {
}

3. 测试

准备工作已经做完了,这个时候我们可以写一个代码测试下,输入框中输入某个值,并在控制台打印出来。如:输入姓名,点击"查询"按钮,控制台输出相应的值。

1
2
3
4
5
6
7
8
/**
 * 查找
 */
search() {
  const nameVal = this.name.nativeElement.value;
  // 输入:'22', 输出: 'name = 22'
  console.log('name = ' + nameVal);
}