angular表单的使用
html:
<h2>人员登记系统</h2> <div class="people_list"> <ul> <li>姓名:<input type="text" [(ngModel)]="peopleInfo.username" class="form_input" /></li> <li> 性别: <input type="radio" value="1" name="sex" [(ngModel)]="peopleInfo.sex" id="sex1" />男 <input type="radio" value="2" name="sex" [(ngModel)]="peopleInfo.sex" id="sex2" />女 </li> <li> 城市: <select name="city" id="city" [(ngModel)]="peopleInfo.city"> <option [value]="item" *ngFor="let item of peopleInfo.cityList;let key=index">{{item}}---{{key}} </option> </select> </li> <li>爱好: <span *ngFor="let item of peopleInfo.hobby;let key=index"> <input type="checkbox" [id]="'check'+key" [(ngModel)]="item.checked" /><label>{{item.title}}</label> </span> </li> <li> 备注: <textarea name="mark" [(ngModel)]="peopleInfo.mark"></textarea> </li> </ul> <div> {{peopleInfo|json}} </div> <button (click)="doSubmit()">点击获取数据</button> </div>
ts:
import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-form', templateUrl: './form.component.html', styleUrls: ['./form.component.scss'] }) export class FormComponent implements OnInit { public peopleInfo:any={ username:'', sex:'1', cityList:['北京','上海','深圳'], city:'北京', hobby:[ { title:'吃饭', checked:false },{ title:'睡觉', checked:false },{ title:'敲代码', checked:true } ], mark:'' } constructor() { } ngOnInit() { } doSubmit(){ console.log(this.peopleInfo.username); } }
app.module.ts
import{FormsModule} from '@angular/forms'; imports: [ FormsModule ],