我是 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);
}
}
在输出中,我可以看到用户名和电子邮件字段,但没有性别字段。
您能帮我解决这个问题吗?
我确信这只是一个小小的改变,但我仍然无法弄清楚。
就我而言,我使用反应式表单并从服务异步加载表单数据。但是,表单模板将开始并行生成。那时表单将是未定义的,因为只有在收到 API 调用的数据后才会构建表单。因此,首先检查表单是否已初始化,然后才开始生成模板。
<form class="col-sm-12 form-content" *ngIf="form" [formGroup]="form">
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)