效果展示:
项目源码:
https://github.com/senhao114/Angulardemo01
创建组件:
ng g component components/form
app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { FormComponent } from './components/form/form.component';
@NgModule({
declarations: [
AppComponent,
FormComponent,
],
imports: [
BrowserModule,
AppRoutingModule,
FormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
styles.scss
/* You can add global styles to this file, and also import other style files */
*{
margin: 0px;
padding: 0px;
}
ul,ol{
list-style: none;
}
app.component.html
<app-form></app-form>
form.component.html
<h2>人员登记系统</h2>
<div class="people_list">
<ul>
<li>姓 名:<input type="text" value="form_input" [(ngModel)]="peopleInfo.username" /></li>
<li>性 别:
<input type="radio" value="1" name="sex" id="man" [(ngModel)]="peopleInfo.sex" /><label for="man"> 男 </label>
<input type="radio" value="2" name="sex" id="woman" [(ngModel)]="peopleInfo.sex" /><label for="woman"> 女</label>
</li>
<li>城 市:
<select name="city" [(ngModel)]="peopleInfo.city">
<option *ngFor="let item of peopleInfo.cityList" [value]="item">{{item}}</option>
</select>
</li>
<li>爱 好:
<span *ngFor="let item of peopleInfo.hobby;let i = index">
<input type="checkbox" [id]="i" [(ngModel)]="item.checked" /><label [for]="i">{{item.title}} </label>
</span>
</li>
<li>备 注:
<textarea id="mark" cols="20" rows="3" [(ngModel)]="peopleInfo.mark"></textarea>
</li>
<li>
<button (click)="doSubmit()">获取表单内容</button>
</li>
</ul>
</div>
form.component.scss
h2{
text-align: center;
margin-top: 40px;
}
.people_list{
border: 1px solid #eeeeee;
width: 300px;
margin: 20px auto;
padding: 20px;
li{
height: 50px;
line-height: 50px;
.frominput{
width: 200px;
height: 20px;
}
}
button{
width: 80px;
height: 20px;
float: right;
margin-right: 40px;
margin-top: 40px;
}
}
form.component.ts
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-form',
templateUrl: './form.component.html',
styleUrls: ['./form.component.scss']
})
export class FormComponent implements OnInit {
peopleInfo :any={
username :'',
sex :'1',
cityList :['北京','上海','深圳'],
city :'北京',
hobby :[{
title:'吃饭',
checked:false
},{
title:'睡觉',
checked:false
},{
title:'写代码',
checked:true
}],
}
constructor() { }
ngOnInit() {
}
doSubmit() {
console.log(this.peopleInfo);
}
}