[英]Angular2: No value accessor for a nested form
我創建了一個帶有嵌套表單組的表單:
this.cardForm = this.fb.group({
number: ['', Validators.compose([Validators.required, this.validateCardNumber])],
holderName: ['', Validators.required],
expiry: this.fb.group({
expirationMonth: ['', Validators.required],
expirationYear: ['', Validators.required],
}, this.validateCardExpiry),
cvc: ['', Validators.required]
});
進入我的模板:
<form [formGroup]="cardForm" novalidate="novalidate" (ngSubmit)="onSave()">
<div class="form-group" formGroupName="expiry">
<label for="expirationmonth">Expiration month</label>
<select2 id="default-select"
name="expirationmonth"
formControlName="expirationMonth"
[data]="months$ | async"
[width]="250"
[options]="select2Options">
</select2>
<label for="expirationyear">Expiration year</label>
<select2 id="default-select2"
name="expirationyear"
formControlName="expirationYear"
[data]="years$ | async"
[width]="250"
[options]="select2Options">
</select2>
</div>
</form>
select2
是ng2-select2的組件。
Angular收到此消息:
錯誤:表單控件的無值訪問器,路徑為:'expiry-> expirationMonth'
因此,您目前必須為此采取一些解決方法。 根據對該問題的最新評論,您可以嘗試做些什么:
我花了一些時間弄清楚使用反應形式。 我要做的就是實現ControlValueAccessor,並在選擇/取消選擇時從ngAfterViewInit傳播更改。
在處理您的代碼時,我發現的另一個解決方法是在選擇ngDefaultControl
上使用ngDefaultControl
。
<select2 ngDefaultControl ..... ></select2>
但是隨之而來的問題是,當您進行更改時,它不會反映在表單值中。 因此,一種快速的解決方法是在值更改時對patchValue
進行更改。 這可能並不漂亮,但是可以。
使用ng2-select2的change事件的模板:
(valueChanged)="changed($event)"
修補值之一的組件:
changed(e) { // e is of primitive type here
this.cardForm.controls['expiry'].controls['expirationMonth'].patchValue(e)
}
嘗試將ngControlDefault
添加到您的<div>
。
<div class="form-group" formGroupName="expiry" ngControlDefault>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.