Angular 错误:formGroup需要一个formGroup实例-向formArray添加新组件时
我用的是反应形式的方法。我有一个表单(父组件名为:Angular 错误:formGroup需要一个formGroup实例-向formArray添加新组件时,angular,typescript,formarray,Angular,Typescript,Formarray,我用的是反应形式的方法。我有一个表单(父组件名为:declarationinvoicescomponent): 表示formArray项的单个组件的TypeScript如下所示: export class DeductionInvoicesComponent implements OnInit { deductionForm: FormGroup; constructor(private fb: FormBuilder) { } ngOnInit() { this.d
declarationinvoicescomponent
):
表示formArray项的单个组件的TypeScript如下所示:
export class DeductionInvoicesComponent implements OnInit {
deductionForm: FormGroup;
constructor(private fb: FormBuilder) { }
ngOnInit() {
this.deductionForm = this.fb.group({
items: this.fb.array([])
});
}
addItem(){
let control = <FormArray>this.deductionForm.controls.items;
control.push(DeductionInvoiceItemComponent.buildItem());
}
}
<div class="row" [formGroup]="item">
<div class="form-group col-4">
<label class="center-block">Title</label>
<select class="form-control" formControlName="title">
<option value="test">test</option>
</select>
</div>
<div class="form-group col-4">
<label class="center-block">Invoice Number</label>
<input class="form-control" formControlName="invoiceNumber">
</div>
<button (click)="removed.emit(index)" type="button" class="close text-danger" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
export class DeductionInvoiceItemComponent {
@Input()
public index: number;
@Input()
public item: FormGroup;
@Output()
public removed: EventEmitter<number> = new EventEmitter<number>();
static buildItem() {
return new FormGroup({
title: new FormControl('', Validators.required),
invoiceNumber: new FormControl('', Validators.required),
grossAmount: new FormControl('', Validators.required)
});
}
}
导出类演绎NVoiceItemComponent{
@输入()
公开索引:编号;
@输入()
公共项目:FormGroup;
@输出()
已删除public:EventEmitter=neweventemitter();
静态buildItem(){
返回新表单组({
标题:新FormControl(“”,需要验证器),
发票编号:新FormControl(“”,需要验证器),
grossAmount:新FormControl(“”,需要验证程序)
});
}
}
当我单击按钮addItem()
时,会收到以下错误消息:
错误:formGroup需要一个formGroup实例
如您所见,我使用名为
buildItem
的静态函数创建了该表单组。如何解决此问题?在您的扣减OICEItem组件中,您有:
@Input()
public item: FormGroup;
但您没有将其作为父组件的输入传递。加上:
<app-deduction-invoice-item
*ngFor="let item of deductionForm.get('items')?.controls; let i=index"
[index]="i"
[item]='item' // <-- HERE
(removed)="deductionForm.get('items').removeAt($event)">
</app-deduction-invoice-item>
哇,这就是问题所在!谢谢!
<app-deduction-invoice-item
*ngFor="let item of deductionForm.get('items')?.controls; let i=index"
[index]="i"
[item]='item' // <-- HERE
(removed)="deductionForm.get('items').removeAt($event)">
</app-deduction-invoice-item>