javascript - 将数据添加到动态创建的字段
问题描述
我正在使用响应式表单来动态添加一些字段并在选择框中显示数据(数组格式的 api 响应),到目前为止,我正在获取表单中的值,但无法设置为选择框。请纠正我我是反应形式的新手。
组件.ts
ngOnInit() {
this.dynamicForm = this.formBuilder.group({
attributes: new FormArray([])
});
}
get f() { return this.dynamicForm.controls; }
get a() { return this.f.attributes as FormArray; }
addAttitubute(){
let array=[]
this.attributeService.getAttributes().subscribe(response =>{
response.forEach(value =>{
array.push(value.name);
})
this.a.push(this.formBuilder.group({
attribute: this.formBuilder.array(array),
value: this.formBuilder.array([])
}));
})
console.log(this.a);
}
html
<label>
<div *ngFor="let t of a.controls; let i = index" class="field-heading">Attribute (e.g. Colour)
<div [formGroup]="t" >
<select formControlName="attribute" required class="attr-dropdown">
<option *ngFor="let value of attribute">
{{ value }}
</option>
</select>
</div>
<div class="flex-one">
<label>
<div class="field-heading">Value (e.g. Red, Blue, Green)</div>
<p-chips inputStyleClass="full-width theme-input" ></p-chips>
</label>
</div>
</div>
</label>
解决方案
您需要将属性和 selectedAttribute 分开。属性用于保存响应 Api 中的值,该值是初始复选框数组值。SelectedAttribute 用于从用户选择中获取选定的值。
推荐阅读
- python - Python collections.Counter,如何避免双重查找
- javascript - 提交时的 JQuery 内容可编辑 div 和文本框
- javascript - onwheel 事件是否由触控板滚动触发
- android - 为什么设计看起来与 android studio 的模拟器中显示的不同?
- android - 我们如何为 navigateUp() 片段过渡设置动画?
- ios - 带有包含collectionview的原型单元格的TableView不返回所有tableviewcells
- javascript - 通过 jQuery 添加内部元素
- r - 使用 pandoc 参数 number-offset 时,在 TOC 中编号,尽管 {-}
- php - 你如何在 laravel 5 中为分页的雄辩查询取回 sum('amount')?
- ios - 快速检查可选数组中的 nil