【发布时间】:2019-09-23 23:41:50
【问题描述】:
我有一个动态反应形式。一部分是通过在 Html 中绑定 FormGroup 和 FormControl 指令来构建的。此外,还有一个单击事件,用于以编程方式将其他值添加到表单值。 问题是,当订阅 this.form.valueChanges observable 时,回调值(lambda 表达式)包括正在添加到 AddToList 函数中的表单值,但它是空的,虽然它之前有值。 每当我更改选择控件中的值时,都会订阅 valueChanges。 无法理解为什么会这样。
<form *ngIf="form" >
<div *ngFor="let col of Colomns">
<ul>
<li *ngFor="let val of col.dataList; let i=index">
<span>{{val}}</span>
<a button type="button" (click)="deleteFromList(i, col.field, $event)">
</a>
</li>
</ul>
</div>
<!--below is the part of binding values using the directives-->
<div *ngFor="let col of Colomns; let i = index">
<div [formGroup]="form">
<select [id]="col.field" [formControlName]="col.field" >
<option [value]=''></option>
<option *ngFor="let sys of col.data" [value]="sys.Code">{{sys.Value}}</option>
</select>
<!-- this is a textbox with an AddToList button-->
<div>
<input class="input" [id]="col.field" type="text" #texttosearch>
<button class="btnAddList" (click)="AddToList(texttosearch.value,
col.field, $event)">
</button>
</div>
</div>
</div>
这是组件所需的代码:
export class dynamicReactiveFrom
{
form: FormGroup;
advanceCols: AdvanceColumnBase<any>[];
constructor(private fb: FormBuilder) { }
initAdvancedSearch(arr:AdvanceColumnBase<any>[])
{
this.advanceCols = arr;
let group: any = {};
arr.forEach(col =>
if (<some condition for the selected Items>)
{
group[col.field] = new FormControl(col.value || '');
}
else/*This is for the items which were added using the AddToList function*/
{
group[col.field] = this.fb.array([this.fb.control('')]);
}
);
this.form = new FormGroup(group);
this.form.valueChanges.subscribe(values => {
/*the value that was set in the AddToList function is now reset, in
the values callback*/
doSeomthing(values);
});
}
AddToList(value: string, field: string, event)
{
event.preventDefault();
let selectedField = this.advanceCols.find( x => x.field === field);
if(selectedField)
{
this.form.value[field] = item.dataList;
}
}
}
从组件外部触发的 initAdvancedSearch 函数具有填充表单所需的值。
【问题讨论】:
标签: angular observable angular-reactive-forms