在Angular中通过 [(ngModel)] 来实现数据的双向绑定
要实现双向数据绑定,首先要引入 FormsModule模块
import { SearchComponent } from './Component/search/search.component';
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { FormsModule } from '@angular/forms'@NgModule({declarations: [AppComponent,SearchComponent,],imports: [BrowserModule,AppRoutingModule,FormsModule,],providers: [],bootstrap: [AppComponent]
})
export class AppModule { }
form.component.html
<h2>人员登记系统</h2>
<div class="people_list"><ul><li>姓名:<input type="text" id="username" [(ngModel)]="peopleInfo.username" value="form_input" [disabled]="flag"/></li><li>性别:<input type="radio" value="1" name="sex" id="sex1" [(ngModel)]="peopleInfo.sex" >男<input type="radio" value="2" name="sex" id="sex2" [(ngModel)]="peopleInfo.sex">女</li><li>城市:<select name="city" id="city" [(ngModel)]="peopleInfo.city"><option [value]="item" *ngFor="let item of peopleInfo.citys">{
{item}}</option></select></li><li>爱好:<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></li><li>备注:<textarea name="mark" id="mark" [(ngModel)]="peopleInfo.mark"></textarea></li></ul><pre>{
{peopleInfo | json}}</pre><button (click)="doSubmit()" >获取表单的内容</button>
</div>
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 flag = false;public peopleInfo:any = {username: '',sex: "1",citys:['北京','上海','深圳'],city: '北京',hobby: [{title: '吃饭',checked: false},{title: '睡觉',checked: false},{title: '敲代码',checked: false}],mark: ""}constructor() { }ngOnInit() {}// doSubmit() {// let nameDom:any = document.getElementById("username");// console.log(nameDom.value);// }doSubmit() {console.log(this.peopleInfo);}
}
运行结果: