我是 Angular 2 的新手,即使在经历了其他堆栈溢出答案之后也无法解决这个问题。
我刚刚开始学习角度反应形式并想尝试第一个示例但被卡住了。请帮忙。
这是 HTML 表单。
<div class="container">
<div class="row">
<div class="col-xs-12 col-sm-10 col-md-8 col-sm-offset-1 col-md-offset-2">
<form [formGroup]="signupForm" (ngSubmit)="onSubmit()">
<div id="user-data">
<div class="form-group">
<label for="username">Username</label>
<input
type="text"
id="username"
formControlName="username"
class="form-control">
</div>
<div class="form-group">
<label for="email">Email</label>
<input
type="email"
id="email"
formControlName="email"
class="form-control">
</div>
<div class="radio" *ngFor="let gender of genders">
<label>
<input
type="radio"
class="form-control"
formControlName="gender"
[value]="gender">{{ gender }}
</label>
</div>
</div>
<button class="btn btn-primary" type="submit">Submit</button>
</form>
</div>
</div>
</div>
这是 TS 文件。
import { Component, OnInit } from '@angular/core';
import { FormGroup } from '@angular/forms';
import { FormControl } from '@angular/forms';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
genders = ['male', 'female'];
// property to hold the form
sigupForm: FormGroup;
ngOnInit() {
// initialize the form before rendering the template
// hence 'OnInit' because this gets executed before the template is rendered// pass js object
// {} tells this form doesn't has any 'controls'
// 'controls' are key-value pairs to the overall form group
this.sigupForm = new FormGroup({
// form controls
// arg1 - intial state/value of this control
// arg2 - single validator or an array of validators
// arg3 - async validators
'username': new FormControl(null),
'email': new FormControl(null),
'gender': new FormControl('male')
});
}
onSubmit() {
console.log(this.sigupForm);
}
}
在输出中,我可以看到用户名和电子邮件字段,但没有性别字段。
你能帮我解决这个问题吗?
我相信这只是一个微小的变化,但我仍然无法弄清楚。