表单双向数据绑定
- 在html中定义表单
```html
人员登记系统
- 姓名:
<!-- 单选框的双向数据绑定 -->
<li>
性别:
<input type="radio" name="sex" id="sex1" value='1' [(ngModel)]="peopleInfo.sex"><label for="sex1">男</label>
<input type="radio" name="sex" id="sex2" value='2' [(ngModel)]="peopleInfo.sex"><label for="sex2">女</label>
</li>
<!-- 下拉框的双向数据绑定 -->
<li>
城市:
<select name="city" id="city" [(ngModel)]="peopleInfo.city">
<option [value]="item" *ngFor="let item of cityList"> {{ item }} </option>
</select>
</li>
<!-- 复选框的双向数据绑定 -->
<li>
爱好:
<span *ngFor="let item of peopleInfo.hobby; let key=index">
<input type="checkbox" name="hobby" [id]="'check' + key" [(ngModel)]='item.checked'> <label [for]="'check' + key"> {{ item.title }} </label>
</span>
</li>
<!-- 多行文本框的双向数据绑定 -->
<li>
备注:
<textarea name="mark" id="mark" cols="30" rows="10" [(ngModel)]='peopleInfo.mark'></textarea>
</li>
</ul>
<br>
<br>
<br>
<br>
<br>
<br>
<!-- 以json样式实时展示peopleInfo对象的内容 -->
```
2. 绘制css样式
```css
h2{
text-align: center;
}
.people_list {
width: 400px;
margin: 20px auto;
padding: 20px;
border: 1px solid #eee;
}
.people_list li {
height: 50px;
line-height: 50px;
}
.people_list li .form-input {
width: 300px;
height: 28px;
}
- 编写ts ```typescript import { Component, OnInit } from ‘@angular/core’;
@Component({ selector: ‘app-form’, templateUrl: ‘./form.component.html’, styleUrls: [‘./form.component.css’] }) export class FormComponent implements OnInit {
// 定义peopleInfo对象,用于存放表单数据
public peopleInfo:any = { username: ‘’, sex:’1’, city:’上海’, hobby: [ { title: ‘吃饭’, checked: false }, { title: ‘睡觉’, checked: false }, { title: ‘敲代码’, checked: true } ], mark:’’ }
// 作为下拉框的选项
public cityList:string[] = [‘北京’, ‘上海’, ‘深圳’];
constructor() { } ngOnInit(): void { }
doSubmit():void { console.log(this.peopleInfo); } } ```