angular—demo表单控件双向数据绑定

使用ngModel语法将对象的属性和表单控件的value进行双向绑定,提交的时候直接提交绑定的对象即可,不用再依次获取表单的值了

1.app.module.ts中引入FormsModule

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

@NgModule({
  declarations: [
    AppComponent,
    FormComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    FormsModule,    // 引入
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

2.创建组件

ng g component components/form

3.定义双向绑定的数据对象

form.component.ts

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-form',
  templateUrl: './form.component.html',
  styleUrls: ['./form.component.css']
})
export class FormComponent implements OnInit {
  // 定义一个对象,属性对应了页面中的表单控件
  public userInfo:any={
    'username': '',    // input
    'sex': 'male',     // radio
    'cityList': ['上海','南京','北京','武汉'],   // select中的option的值
    'city': '南京',    // select最终选择的值
    'hobby': [        // checkbox
      {'title': '吃饭', 'checked': false},
      {'title': '睡觉', 'checked': false},
      {'title': '打豆豆', 'checked': false},
      {'title': '写bug', 'checked': true},
    ],
    'introduce': ''    // textarea
  }
  constructor() { }

  ngOnInit() {
  }

  // button绑定的点击事件
  onSubmit() {
    console.log(this.userInfo);
  }
}

4.页面中进行绑定

<div>
    <h1>人员登记系统</h1>
    <div class="form">
        <!-- 表单元素,双向绑定userInfo对象的属性 -->
        <li>
            姓名<input type="text" class="form-input" [(ngModel)]="userInfo.username">
        </li>

        <li>
            性别:
            <input type="radio" value='male' id="form-male" [(ngModel)]="userInfo.sex" name="sex">
            <label for="form-male"></label>
            <input type="radio" value='female' id="form-female" [(ngModel)]="userInfo.sex" name="sex">
            <label for="form-female"></label>
        </li>
        
        <li>
            地区:
            <select name="city" id="" [(ngModel)]="userInfo.city">
                <option [value]="item" *ngFor="let item of userInfo.cityList">{{item}}</option>
            </select>
        </li>

        <li>
            爱好:
            <span *ngFor="let item of userInfo.hobby;let key=index">
                <input type="checkbox" name='hobby' [id]="'check'+key" [(ngModel)]="item.checked">
                <label [for]="'check'+key">{{item.title}}</label>
            </span>
        </li>

        <li>
            简介:
            <textarea [(ngModel)]="userInfo.introduce" cols="35" rows="5"></textarea>
        </li>
        <br>
        <br>
        <button (click)="onSubmit()">提交</button>
        
    </div>
</div>

参考:https://www.bilibili.com/video/av59049211?from=search&seid=485997827014437418

发布了106 篇原创文章 · 获赞 8 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/weixin_43667990/article/details/103780745
今日推荐