[英]Can't bind to dynamically added input in Bootstrap modal of Angular component
首先,我不知道模態與這個問題有什么關系,因為它實際上在該組件的代碼中,而不是在子代碼中。 盡管如此,以防萬一。
我選擇不使用FormArray,因為我需要跟蹤可能添加到單獨對象中的選擇,因此我只是為控件創建唯一的ID,並將其添加到FormGroup。 我可以訪問ts代碼中的控件,設置值,獲取值等,但是表單沒有綁定,我不知道為什么不這樣做。
在這種模式形式下,我可以有數量未知的項目,每個項目都有一個選擇器(用於選擇屬性的下拉菜單),然后是能夠修改某些數據的輸入。 輸入的類型可能不同,因此需要根據選擇器的選擇進行添加和綁定。
<form [formGroup]="multiEditFormGroup" novalidate>
<div *ngFor="let item of multiEditSelections; let i = index">
<div>
<mdb-select [options]="availablePropsSelect"
placeholder="Choose property to edit"
class="colorful-select dropdown-main"
(selected)="multiEditSelectProp(item.selectorId, $event)"></mdb-select>
<label>Property to edit</label>
</div>
<div>
<div>
<input mdbActive
type="text"
class="form-control"
[formControlName]="item.controlId" />
</div>
</div>
</div>
</form>
ts代碼除外:
public multiEditFormGroup = new FormGroup({});
onModalOpen():void {
const selectorId = this.utils.uuid();
this.multiEditFormGroup.addControl(selectorId, this.propSelector);
this.multiEditSelections.push({
selectorId: selectorId,
prop: '',
label: '',
type: '',
controlId: '' // not yet known since type hasn't been chosen
});
}
onSelect(selectorId: string, selectEvent: any): void {
let selection = this.multiEditSelections.find(selection => {
return selection.selectorId === selectorId;
});
const controlId = this.utils.uuid();
const prop = selectEvent.value;
this.multiEditFormGroup.get(selection.selectorId).setValue(prop);
this.multiEditFormGroup.markAsDirty();
this.multiEditFormGroup.markAsTouched();
const model = this.multiEditModel.find(model => {
return model.prop === prop;
});
this.multiEditFormGroup.addControl(controlId, this.testCtrl);
selection.controlId = controlId;
selection.prop = prop;
selection.label = model.label;
selection.type = model.type;
}
登錄到控制台顯示,已將項目添加到FormGroup,但未對DOM進行綁定。 例如,我可以在輸入中添加一個(keyup)
事件處理程序,並在已經創建的窗體控件中設置該值,並更新FormGroup。 但是,前端中添加的任何輸入都不會更新FG,因為它顯然沒有綁定。 這是時間問題還是因為controlId稍后要更新? 我正在創建FormControl,然后再更新要迭代的數組。
哦,我在控制台上沒有任何錯誤。
我認為您需要進行此更改:
[formControlName]="item.controlId"
需要是:
formControlName="{{item.controlId}}"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.