我正在尝试创建一个包含多个对象的角形数组,每个对象具有5个属性。我从firestore中检索对象数组,并将其传递给表单组,我正在努力解决的问题是如何为每个不同的对象及其属性添加控件。我已附上我到目前为止的摘要。
第一个图片是我传递给表单的对象数组,该对象使用
以html格式打印{{m1t1Form.value | json}}
Value: { "players": [ { "kills": 0, "deaths": 0, "damage": 0, "id": "JVnUQRv1YBt9D7JIkWvn", "playerID": "dAS3YyQvTX8ILQQPRxO3" }, { "kills": 0, "deaths": 0, "damage": 0, "id": "OwFBLDgQxDv86TiA2Urc", "playerID": "8ZCqn1NEqPSFchoPjigY" }, { "kills": 0, "deaths": 0, "damage": 0, "id": "UBnQmwiRJwF2HgNYvqGn", "playerID": "xkGVBqn3Pv50vVa5iiO1" }, { "kills": 0, "deaths": 0, "damage": 0, "id": "q4kHgwENnVTuvEIRUpUe", "playerID": "qmKJc03aqmfgAWrZQRzO" }, { "kills": 0, "deaths": 0, "damage": 0, "id": "qh8ZKPLpd64Cq4Ixw6Aa", "playerID": "OLJr4qvdOlFgIcb66iSI" } ] }
答案 0 :(得分:3)
嗨,这可能对您绑定我在项目中使用过的表格很有帮助。
constructor( private formBuilder: FormBuilder)
{
this.m1t1Form = formBuilder.group({
'players' : formBuilder.array([])
});
}
}
ngAfterViewInit()
{
for (let i = 0; i < valueObject.players.length; i++)
{
const control = <FormArray>this.m1t1Form.controls['players'];
control.push(this.initPlayerForm(valueObject.players[i]));
}
}
initPlayerForm(playerVO : player)
{
return this.formBuilder.group({
'kills': [player.kills],
'death': [player.death],
'damage': [player.damage],
'id': [player.id],
'playerId': [player.playerId]
});
}
通过这种方式,您可以与任意数量的播放器动态绑定表单。添加验证也很有帮助。
答案 1 :(得分:2)
我具有相同的功能。下面的代码将为您提供帮助。
HTML代码:
<form [formGroup]="m1t1Form" class="form-horizontal">
<div class="form-group">
<div class="col-md-10">
<div formArrayName="players" *ngFor="let player of m1t1Form.get('players').controls; let i = index;">
<div [formGroupName]="i">
<div class="col-md-5">
<input class="form-control col-md-5" formControlName="kills" placeholder="kills">
</div>
<div class="col-md-5">
<input type="text" placeholder="death" class="form-control col-md-5"
formControlName="death">
</div>
<button class="btn btn-info btn-xs m-t-sm" type="button" (click)="getPlayerDetails(i)">
<i name="save" class="fa fa-eye"></i>
</button>
</div>
</div>
</div>
</div>
</form>
TS代码:
m1t1Form: FormGroup;
players: FormArray;
ngOnInit(){
// Default adding one object
this.m1t1Form= new FormGroup({
'players': new FormArray([this.createItem()])
});
// Load you data from service
let playersData : any[] = []; // Fille data
// Create control dynamically and set value from service data to form
if (playersData .length > 0) {
this.players= this.m1t1Form.get('players') as FormArray;
while (this.players.length) {
this.players.removeAt(0);
}
this.m1t1Form.patchValue(this.playersData );
playersData .forEach(player=>
this.players.push(this.formBuilder.group(player)));
}
}
createItem(): FormGroup {
return new FormGroup({
id: new FormControl(),
kills: new FormControl(),
death: new FormControl()
});
}
getPlayerDetails(index: any) {
if (this.players.at(index).get('id').value) {
// Do whatever you want to do with id or playerId
}
}