应用需求使用 ng 实现用户注册功能,废话不多说,需求比较简单不在描述,页面构建原型大概如下图所示:
同样先使用Angular CLI脚手架命令创建一个项目demo01, 依次构建组件【userRegistrationInfo】:
- html 页面构建如下:
<hr/>
<h3 [ngClass]="{'h3': isTrue}">表单实现【MVVM】双向数据绑定</h3>
<section>
<p class="h3">
管道解析,注册数据模型 =》 {{userRegistInfo | json}}
</p>
<ul [ngStyle]="{'border': '2px solid #369', 'max-width': '300px'}">
<li [ngStyle]="{'text-align': 'center'}"> 【用户信息注册】 </li>
<li>
用户名称:<input type="text" name="userName" id="userName" [(ngModel)]="userRegistInfo.userName" />
</li>
<li>
电话号码:<input type="tel" name="telNum" id="telNum" [(ngModel)]="userRegistInfo.telNum" />
</li>
<li>
性别:
<span *ngFor="let item of userRegistInfo.sexList; let i=index;">
<input type="radio" name="sex" [id]="'p'+i" [value]="item" [(ngModel)]="userRegistInfo.sex" />
<label [for]="'p'+i"> {{item}} ----- {{i + 1}} </label>
</span>
</li>
<li>
所在城市:
<select name="citys" id="citys" [(ngModel)]="userRegistInfo.city">
<option value="">--请选择--</option>
<option [value]="tmpCity" *ngFor="let tmpCity of userRegistInfo.cityList;"> {{tmpCity}} </option>
</select>
</li>
<li>
兴趣爱好:<br/>
<span *ngFor="let item of userRegistInfo.xinQuAiHaoList; let i=index;">
<input type="checkbox" [name]="'aihao'+i" [id]="'aihao'+i" [value]="item.title" [(ngModel)]="item.checked" /> <label [for]="'aihao'+i"> {{item.title}} </label>
</span>
</li>
<li>
备注:<br/>
<textarea name="remark" id="remark" cols="36" rows="6" [(ngModel)]="userRegistInfo.remark" ></textarea>
</li>
<li>
<button (click)="getData()">确定</button> <button (click)="setData()">重置</button> <br/><br/>
</li>
</ul>
<p> {{submitMsg}} </p>
</section>
- ts 代码构建如下:
public submitMsg:string; //提示信息
//用户注册模型Model=>View(html)
public userRegistInfo:object = {
userName:'',
telNum:123,
sexList:['男','女'],
sex:'女',
cityList:['北京','上海','深圳','重庆','云南'],
city:'',
xinQuAiHaoList:[{
title:'逛街',
checked: false
},
{
title:'美食',
checked: true
},
{
title:'运动',
checked: false
},
{
title:'听歌',
checked: true
},
{
title:'电影',
checked: false
},
{
title:'看书',
checked: false
}],
remark: '备注'
};
//确定
getData():void {
console.log(this.userRegistInfo);
this.submitMsg = '数据提交中。。。';
var isOk:boolean = confirm('是否确定提交?提交数据如下:'+ JSON.stringify(this.userRegistInfo));
if (isOk) {
this.submitMsg = '数据提交成功!';
}else{
this.submitMsg = '数据提交失败或者被取消提交!';
}
}
//重置
setData():void {
this.userRegistInfo = {
userName:'',
telNum:10086,
sexList:['男','女'],
sex:'女',
cityList:['北京','上海','深圳','重庆','云南'],
city:'',
xinQuAiHaoList:[{
title:'逛街',
checked: false
},
{
title:'美食',
checked: false
},
{
title:'运动',
checked: false
},
{
title:'听歌',
checked: false
},{
title:'电影',
checked: false
}],
remark: '备注'
};
}
- css 代码构建:
.ul{ border: 1px solid red; max-width: 300px;}
.h3{ color:orange; }
#p1{ background-color: peru;}
li{ padding:0;margin:0;list-style:none; }
构建好后,把用户注册组件挂载在【app.component.html】页面,同时记得在【app.module.ts】文件中引入 【MVVM】所需模块【FormsModule】并声明:
import { FormsModule } from '@angular/forms'; //MVVM 需要导入
//***同时在@NgModule的imports中声明该模块FormsModule
最终运行页面显示如下效果:
大功告成,有感兴趣的小伙伴可以参照上面案例动手实践哦!