angular项目表单实例(一)

实例效果如:

组件页面html代码:

<h2>测试表单模板</h2>
<div [class]="{'divclas':true}">
    <ul>
        <li>
            姓名:<input type="text" id="username" [(ngModel)]="user.username" [ngClass]="{'nameclas':true}" />
        </li>
        <li>
            性别:<input type="radio" value="1" name="sexx" [(ngModel)]="user.sex" id="sex1"><label for="sex1"></label>
            <input type="radio"  value="2" name="sexx" [(ngModel)]="user.sex" id="sex2"><label for="sex2"></label>
        </li>
        <li>
            城市:
            <select [(ngModel)]="user.city">
                <option [value]="item" *ngFor="let item of user.citylist">{{item}}</option>
            </select>
        </li>
        <li>
            爱好:
            <span *ngFor="let item of user.likeslist;let key = index">
                <input type="checkbox" [id]='"check"+key' [(ngModel)]="item.checked" /><label [for]="'check'+key">{{item.title}}</label>
                &nbsp;&nbsp;&nbsp;
            </span>
        </li>
    </ul>
    <button [ngClass]="{'butclas':true}" (click)="getsubmit()">查看/隐藏内容</button>
</div>
<div [class]="{'divresultclas':true}"  [hidden]="hid">
    <pre>
    {{user | json}}
    </pre>
</div>

ts逻辑代码:

public user:any = {
    username: "111",
    sex: "2",
    city:"北京",
    likeslist: [{
      title: '吃饭',
      checked: false
    }, {
      title: '喝水',
      checked: false
    }, {
      title: '玩',
      checked: true
    }],
    citylist: ["北京", "上海", "广州"]
  };
  public namess:string="2342"
  public hid:any = true;
  ngOnInit(): void {
  }
  getsubmit(){
    this.hid = !this.hid;
  }

css样式代码:

h2{
    text-align: center;
}
.divclas{
    border: 1px solid red;
    width: 400px;
    margin: 0 auto;
    padding:10px;
}
.divresultclas{
    border: 1px solid red;
    width: 400px;
    margin: 0 auto;
    padding:10px;
    margin-top: 50px;
}
.divclas li{
    height: 50px;
    line-height: 50px;
}
.nameclas{
    width:300px;
    height: 30px;
}
.butclas{
    margin-right: 30%;
    margin-top: 20px;
    width: 100px;
    height: 30px;
    float: right;
}

知识点:

使用双向绑定必须在根模块儿中引入表单相关的模块儿,才可以使用双向数据绑定

import {FormsModule} form '@angular/forms';

必须声明配置表单模块儿

@NgModule({imports:[FormsModule(添加表单模块儿)]})。

中括号表示动态属性,小括号绑定事件。

双向绑定:[(ngModel)]="属性名称"

动态绑定类名:[ngClass]=“{‘nameclas’:true}”,格式第一个参数为类名,第二个参数表示是否生效

<label>模块儿化汉字,实现点击汉字勾选中状态。
循环数组:*ngForm="let item of lists;let key=index",格式let 变量名 of 数组;let 变量名=index用变量名获取并使用下标
<pre>格式化文本,如下
 
原文地址:https://www.cnblogs.com/mangwusuozhi/p/13440188.html