Pra*_*ena 8 typescript angular angular-reactive-forms formgroups
我是 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>
Run Code Online (Sandbox Code Playgroud)
这是 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);
}
}
Run Code Online (Sandbox Code Playgroud)
在输出中,我可以看到用户名和电子邮件字段,但没有性别字段。
你能帮我解决这个问题吗?
我相信这只是一个小改动,但我仍然无法弄清楚。
formGroup expects a FormGroup instance 意味着您没有为模板中定义的 FormGroup 创建实例 signupForm
所以你必须创建一个这样的实例signupForm:
this.signupForm = 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')
});
Run Code Online (Sandbox Code Playgroud)
就我而言,我使用的是响应式表单并从服务异步加载表单数据。但是,表单模板将开始并行生成。那时表单将是未定义的,因为它只有在收到来自 API 调用的数据后才会构建。因此,首先检查表单是否已初始化,然后才开始生成模板。
<form class="col-sm-12 form-content" *ngIf="form" [formGroup]="form">
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
16494 次 |
| 最近记录: |