角度2:包含子组件的表单 [英] Angular 2: Form containing child component
问题描述
我有一个具有表单的组件和该表单中的一些子组件.子组件是使用*ngFor
创建的,每个子组件都包含input
元素. Angular2编译器给出类似[formGroup]的错误.
I have component which has a form and some child components within the form. The child components are created using *ngFor
and each child contains input
elements. Angular2 compiler is giving errors like [formGroup] is not defined.
此实现正确吗?
父项:
<section class="data-body">
<form [formGroup]="checkoutForm" novalidate>
<app-checkout-product-view *ngFor="let item of checkoutData.products" [_product]="item" formGroupName="products"></app-checkout-product-view>
<div class="col-md-4">
<label>Nominee:</label>
<select required [(ngModel)]="checkoutData.selectedNominee" [ngModelOptions]="{standalone: true}">
<option *ngFor="let nominee of checkoutData.nomineeList" [value]="nominee">{{nominee}}</option>
</select>
</div>
<div class="col-md-4">
<label>Bank Account:</label>
<select [(ngModel)]="checkoutData.selectedBank" required [ngModelOptions]="{standalone: true}">
<option *ngFor="let bank of checkoutData.bankList" [value]="bank">{{bank}}</option>
</select>
</div>
</div>
</form>
</section>
子组件:app-checkout-product-view
<div class="row">
<div class="col-md-4">
<md-input required [(ngModel)]="product.investmentAmount
formControlName="investmentAmount">
<span md-prefix>₹</span><!--Rupee icon-->
</md-input>
</div>
</div>
P.S. :所有导入都很好,所以我很确定这里没有导入错误
P.S. : All the imports are fine so I am pretty sure that no import errors here
推荐答案
此行为是预期的.在嵌套组件中时,不会自动注册角度形式.但是,您可以通过为子组件提供外部FormGroup来解决此问题.在子组件内部,将模板包装在同一组中.这可能是这样的:
This behavior is expected. Angular forms are not automatically registered when inside nested component. However you can workaround this by providing the outer FormGroup to the child component. And inside the child component wrap the template inside that same group. Here is how this might look:
/外部组件代码-它包含表单/
/outer component code - it contains the form/
@Component({
selector: 'my-app',
template: `
<form [formGroup]="reactiveFormGroup">
<input formControlName="foo" />
<my-comp **[group]="reactiveFormGroup"**></my-comp>
</form>
form value: {{ reactiveFormGroup.value | json }}
`
})
export class AppComponent {
reactiveFormGroup = new FormGroup({
foo: new FormControl('default foo'),
bar: new FormControl('default bar')
});
}
/子组件代码,即my-comp/
/child component code, i.e my-comp/
@Component({
selector: 'my-comp',
template: `
<div [formGroup]="group">
<input [formControlName]="'bar'" />
</div>
`
})
export class MyComponent {
@Input() group: FormGroup;
}
这篇关于角度2:包含子组件的表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!