Angular 2 - 表单组组件 [英] Angular 2 - form group component
本文介绍了Angular 2 - 表单组组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试构建一个数据驱动的表单,输入来自另一个组件,如下所示:
app-form-group
组件看起来像这样:
<label class="col-md-2 control-label">{{Name}}</label><div class="col-md-9"><input class="form-control" [name]="name" [formControlName]="formCtrlName">
问题是 formControlName
需要一个 formGroup
指令,因此我收到此错误:
Error : Error in ./FormGroupComponent class FormGroupComponent - 内联模板:3:58 由以下原因引起:formControlName 必须与父 formGroup 指令一起使用.您需要添加一个 formGroup指令并将其传递给现有的 FormGroup 实例(您可以在类中创建一个).
有什么办法可以解决这个问题吗?
解决方案
你应该在 app-form-group
组件中使用你的 FormGroup [formGroup]="signupForm"
.您可以使用此代码:
<label class="col-md-2 control-label">{{Name}}</label><div class="col-md-9"><input class="form-control" [name]="name" [formControlName]="formCtrlName">
I'm trying to build a data-driven form, with inputs coming from another component, like this:
<form [formGroup]="signupForm" (ngSubmit)="onSubmit()">
<app-form-group [name]="name"></app-form-group>
<app-form-group [name]="email"></app-form-group>
<app-form-group [name]="other"></app-form-group>
</form>
The app-form-group
component will look something like this:
<div class="form-group">
<label class="col-md-2 control-label">{{Name}}</label>
<div class="col-md-9">
<input class="form-control" [name]="name" [formControlName]="formCtrlName">
</div>
The problem is that formControlName
needs a formGroup
directive, therefore I get this error:
Error : Error in ./FormGroupComponent class FormGroupComponent - inline template:3:58 caused by: formControlName must be used with a parent formGroup directive.You'll want to add a formGroup
directive and pass it an existing FormGroup instance (you can create one in your class).
Is there any way to get around this issue?
解决方案
You should use your FormGroup [formGroup]="signupForm"
in app-form-group
Component.You can use this Code :
<div class="form-group" [formGroup]="signupForm">
<label class="col-md-2 control-label">{{Name}}</label>
<div class="col-md-9">
<input class="form-control" [name]="name" [formControlName]="formCtrlName">
</div>
这篇关于Angular 2 - 表单组组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文