我正在动态创建两个字段,一个是选择框,另一个是p芯片(就像标签一样),现在我想将所有具有选择框id的标签插入formArray中,如果我传递p-返回的数组芯片在创建字段时会跳过第一个条目,因为当时数组为空。请检查img和代码,以更好地理解它们。
component.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" class="attr-dropdown">
<option *ngFor="let value of attribute" [ngValue]="value.id">
{{ value.name }}
</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" (onAdd)="myfunc($event)"></p-chips>
</label>
</div>
</div>
</label>
<div class="add-variantes-row">
<a >
<div class="add-variant-btn"> + </div>
<div class="ml-2 pointer" (click)="addAttitubute()">Add attribute</div>
</a>
</div>
component.ts
ngOnInit() {
this.dynamicForm = this.formBuilder.group({
attributes: new FormArray([])
});
}
get f() { return this.dynamicForm.controls; }
get a() { return this.f.attributes as FormArray; }
myfunc(event){
this.array.push(event.value);
console.log(this.dynamicForm.controls.attributes);
}
addAttitubute(){
this.attributeService.getAttributes().subscribe(response =>{
this.attribute=response;
this.a.push(this.formBuilder.group({
attribute: new FormControl (""),
value: this.formBuilder.array(this.array)
}));
this.array=[];
})
}