![](/img/trans.png)
[英]How to iterate over FormArray in FormGroup in an Angular reactive Form
[英]How to get unique value in FormArray reactive form in Angular?
我創建了一個stackblitz應用程序,以在此處演示我的問題: https ://angular-ry1vc1.stackblitz.io/
我在選擇HTML列表上有formArray值。 每當用戶更改選擇時,它都應在頁面上顯示選擇的值。 問題是我如何只顯示當前選擇,而不能覆蓋以前選擇的值。 我想知道如何使用key
來使值的占位符唯一。 TIA
form.html
<form [formGroup]="heroForm" novalidate class="form">
<section formArrayName="league" class="col-md-12">
<h3>Heroes</h3>
<div class="form-inline" *ngFor="let h of heroForm.controls.league.controls; let i = index" [formGroupName]="i">
<label>Name</label>
<select (change)="onSelectingHero($event.target.value)">
<option *ngFor="let hero of heroes" [value]="hero.id" class="form-control">{{hero.name}}</option>
</select> <hr />
<div>
Hero detail: {{selectedHero.name}}
</div> <hr />
</div>
<button (click)="addMoreHeroes()" class="btn btn-sm btn-primary">Add more heroes</button>
</section>
</form>
component.ts
import { Component, OnInit } from '@angular/core';
import { FormArray, FormBuilder, FormControl, FormGroup, Validators, NgForm } from '@angular/forms';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit {
heroes = [];
heroForm: FormGroup;
selectedHero;
constructor(
private fb: FormBuilder,
) {
this.heroForm = fb.group({
league: fb.array([
this.loadHeroes(),
this.loadHeroes(),
this.loadHeroes()
])
});
}
ngOnInit() {
this.listHeroes();
}
public addMoreHeroes() {
const control = this.heroForm.get('league') as FormArray;
control.push(this.loadHeroes());
}
public loadHeroes() {
return this.fb.group(
{
id: this.heroes[0],
name: '',
level: '',
skill: '',
}
);
}
public listHeroes() {
this.heroes = [
{
id: 1,
name: 'Superman'
},
{
id: 2,
name: 'Batman'
},
{
id: 3,
name: 'Aquaman'
},
{
id: 4,
name: 'Wonderwoman'
}
];
}
public onSelectingHero(heroId) {
this.heroes.forEach((hero) => {
if(hero.id === +heroId) {
this.selectedHero = hero;
}
});
}
}
如果這樣做的目的是按數組元素僅顯示選定的英雄,而不是替換所有選定的值,那么您可以使用數組表單元素獲得一些幫助。
答 onSeletingHero
和selectedHero
不是必要的,我所取代,使用通過表單值formControlName
屬性,在該示例中, id
控制是select
。 h.value.id
是獲取所選值ID的方法。
<select formControlName="id">
<option *ngFor="let hero of heroes;" [value]="hero.id" class="form-control">{{hero.name}}</option>
</select> <hr />
<div>
Hero detail: {{getHeroById(h.value.id).name}}
</div> <hr />
</div>
B.為了獲得選中的英雄,我添加了getHeroById
方法。
getHeroById(id: number) {
return id ? this.heroes.find(x => x.id === +id) : {id: 0, name: ''};
}
希望這些信息能解決您的問題。 干杯
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.