33Angular实现人员登记系统(表单元件的双向数据绑定)
1 <h1>人员登记系统</h1> 2 <div class="form"> 3 <ul> 4 <li> 5 <label for="userName">姓名:</label><input type="text" id="userName" [(ngModel)]="peopleInfo.uName" /> 6 </li> 7 <li> 8 性别: 9 <label for="sex1">男</label> <input type="radio" value='1' name="sex" [(ngModel)]="peopleInfo.sex" id="sex1"> 10 <label for="sex2">女</label> <input type="radio" value='2' name="sex" [(ngModel)]="peopleInfo.sex" id="sex2"> 11 </li> 12 <li> 13 <label for="cityList">城市:</label> 14 <select name="cityList" id="cityList" [(ngModel)]="peopleInfo.city"> 15 <option [value]="item" *ngFor="let item of peopleInfo.cityList">{{item}}</option> 16 </select> 17 </li> 18 <li> 19 <label for="hobby">爱好:</label> 20 <span *ngFor="let item of peopleInfo.hobbyList; let key = index;"> 21 <input type="checkbox" [id]="key" [(ngModel)]="item.checked"> <label [for]="key">{{item.title}}</label> 22 </span> 23 </li> 24 <li> 25 <label for="note">备注:</label> 26 <textarea name="note" id="note" cols="30" rows="7" [(ngModel)]="peopleInfo.note"></textarea> 27 </li> 28 </ul> 29 <button (click)="getInfo()">获取人员信息</button> 30 </div> 31 32 <div class="pre"> 33 {{peopleInfo | json}} 34 </div>
1 import { Component, OnInit } from '@angular/core'; 2 3 @Component({ 4 selector: 'app-form', 5 templateUrl: './form.component.html', 6 styleUrls: ['./form.component.css'] 7 }) 8 export class FormComponent implements OnInit { 9 peopleInfo:object={ 10 uName:'', 11 sex:'', 12 cityList:['北京','上海','天津','重庆'], 13 city:'上海', 14 hobbyList:[ 15 { 16 title:'唱歌', 17 checked:true, 18 }, 19 { 20 title:'跳舞', 21 checked:false 22 }, 23 { 24 title:'敲代码', 25 checked:false 26 }, 27 { 28 title:'睡觉', 29 checked:false, 30 } ], 31 note:'', 32 } 33 34 constructor() { } 35 36 ngOnInit() { 37 } 38 39 getInfo(){ 40 console.log(this.peopleInfo); 41 } 42 43 }