0、进行form表单双向数据绑定的前提:
在app.module.ts中引入
//引入表单相关的模块 才可以用双休数据绑定
import { FormsModule } from '@angular/forms';
imports: [
BrowserModule,
FormsModule
]
1、input组件
<li>姓 名:<input type="text" id="username" [(ngModel)]="peopleInfo.username" value="fonm_input" /></li>
2、radio组件
<li>性 别:
<input type="radio" value="1" name="sex" id="sex1" [(ngModel)]="peopleInfo.sex"> <label for="sex1">男 </label>
<input type="radio" value="2" name="sex" id="sex2" [(ngModel)]="peopleInfo.sex"> <label for="sex2">女 </label>
</li>
public peopleInfo:any={
username:'',
sex:'2',
cityList:['北京','上海','深圳'],
city:'上海',
hobby:[{
title:'吃饭',
checked:false
},{
title:'睡觉',
checked:false
},{
title:'敲代码',
checked:true
}],
mark:''
}
3、select组件
城 市:
<select name="city" id="city" [(ngModel)]="peopleInfo.city">
<option [value]="item" *ngFor="let item of peopleInfo.cityList">{{item}}</option>
</select>
public peopleInfo:any={
username:'',
sex:'2',
cityList:['北京','上海','深圳'],
city:'上海',
hobby:[{
title:'吃饭',
checked:false
},{
title:'睡觉',
checked:false
},{
title:'敲代码',
checked:true
}],
mark:''
}
4、checkbox组件
爱 好:
<!--
*ngFor :循环后台数据,key定义index
[id]:动态绑定id
[(ngModel)]:双向数据绑定数据item.checked
[for]:
-->
<span *ngFor="let item of peopleInfo.hobby;let key=index;">
<input type="checkbox" [id]="'check'+key" [(ngModel)]="item.checked"/> <label [for]="'check'+key"> {{item.title}}</label>
</span>
public peopleInfo:any={
username:'',
sex:'2',
cityList:['北京','上海','深圳'],
city:'上海',
hobby:[{
title:'吃饭',
checked:false
},{
title:'睡觉',
checked:false
},{
title:'敲代码',
checked:true
}],
mark:''
}
5、textarea组件
<textarea name="mark" id="mark" cols="30" rows="10" [(ngModel)]="peopleInfo.mark"></textarea>
public peopleInfo:any={
username:'',
sex:'2',
cityList:['北京','上海','深圳'],
city:'上海',
hobby:[{
title:'吃饭',
checked:false
},{
title:'睡觉',
checked:false
},{
title:'敲代码',
checked:true
}],
mark:''
}
6、js对象在页面显示为json串的管道
{{peopleInfo | json}}
7、提交表单按钮
<button (click)="doSubmit()" class="submit">获取表单的内容</button>
doSubmit(){
/*
jquery dom操作
<input type="text" id="username" />
let usernameDom:any=document.getElementById('username');
console.log(usernameDom.value);
*/
console.log(this.peopleInfo);
}