表单双向数据绑定

  1. 在html中定义表单 ```html

    人员登记系统

  • 姓名:
    1. <!-- 单选框的双向数据绑定 -->
    2. <li>
    3. 性别:
    4. &nbsp;&nbsp;&nbsp;&nbsp;
    5. <input type="radio" name="sex" id="sex1" value='1' [(ngModel)]="peopleInfo.sex"><label for="sex1"></label>
    6. &nbsp;&nbsp;&nbsp;&nbsp;
    7. <input type="radio" name="sex" id="sex2" value='2' [(ngModel)]="peopleInfo.sex"><label for="sex2"></label>
    8. </li>
    9. <!-- 下拉框的双向数据绑定 -->
    10. <li>
    11. 城市:
    12. <select name="city" id="city" [(ngModel)]="peopleInfo.city">
    13. <option [value]="item" *ngFor="let item of cityList"> {{ item }} </option>
    14. </select>
    15. </li>
    16. <!-- 复选框的双向数据绑定 -->
    17. <li>
    18. 爱好:
    19. &nbsp;&nbsp;
    20. <span *ngFor="let item of peopleInfo.hobby; let key=index">
    21. <input type="checkbox" name="hobby" [id]="'check' + key" [(ngModel)]='item.checked'> <label [for]="'check' + key"> {{ item.title }} </label>
    22. &nbsp;&nbsp;
    23. </span>
    24. </li>
    25. <!-- 多行文本框的双向数据绑定 -->
    26. <li>
    27. 备注:
    28. <textarea name="mark" id="mark" cols="30" rows="10" [(ngModel)]='peopleInfo.mark'></textarea>
    29. </li>
    30. </ul>
    31. <br>
    32. <br>
    33. <br>
    34. <br>
    35. <br>
    36. <br>
    37. <!-- 以json样式实时展示peopleInfo对象的内容 -->

    1. ```
    2. 2. 绘制css样式
    3. ```css
    4. h2{
    5. text-align: center;
    6. }
    7. .people_list {
    8. width: 400px;
    9. margin: 20px auto;
    10. padding: 20px;
    11. border: 1px solid #eee;
    12. }
    13. .people_list li {
    14. height: 50px;
    15. line-height: 50px;
    16. }
    17. .people_list li .form-input {
    18. width: 300px;
    19. height: 28px;
    20. }
    1. 编写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 {

    1. // 定义peopleInfo对象,用于存放表单数据

    public peopleInfo:any = { username: ‘’, sex:’1’, city:’上海’, hobby: [ { title: ‘吃饭’, checked: false }, { title: ‘睡觉’, checked: false }, { title: ‘敲代码’, checked: true } ], mark:’’ }

    1. // 作为下拉框的选项

    public cityList:string[] = [‘北京’, ‘上海’, ‘深圳’];

    constructor() { } ngOnInit(): void { }

    doSubmit():void { console.log(this.peopleInfo); } } ```