我想創建我的第一個Angular 2應用程序。像往常一樣,我立即遇到了我想創建的模型的麻煩。我有一個模型來創建artilces之間的父子關係。 例如:我想補充的文章,我的購物籃一些子對象如下:角度2/4反應形式與陣列
IArticle[] = [
{
id: 1,
parentArticle: 1234596,
description: 'some description for parent'
children: [
{
id: 1,
childArticle: 123457,
childDescription: 'some description for first child'
},
{
id: 2,
childArticle: 123467,
childDescription: 'some description for second child'
},
.....
]
在打字稿我定義的接口爲我的文章。子對象有自己的界面,這個界面略有不同。
由於這些子對象是一個小的固定集,我想使用下拉列表添加這些子對象。我希望這些對象在點擊時顯示爲帶有刪除的按鈕(可選用帶有「你確定」的模式彈出的問題)。所以我認爲下拉列表旁邊的按鈕應該將下拉列表值添加到數組中。這工作正常時,我將值添加到正常的類型數組。但是現在我想用「Reactive Form」來包裝這個數組。
有人可以幫助我如何使用這些Reactive窗體中的數組以及如何將它們包裝在FormControl對象中。我看着FormArray的「控制」,但不知道這是我在尋找什麼。它接收一組FormControls,而不是一組數據。也許Reactive Forms不是正確的決定?希望有人能把我放在正確的軌道上。
我的HTML模板如下(從代碼剝離引導代碼)
<form autocomplete="off">
<input type="text" Placeholder="Article Number" />
<div >
<button *ngFor="let child of children">
<span class="glyphicon glyphicon-remove-circle text-danger"></span>
{{ child.childArticle }}
</button>
</div>
<div >
<select class="form-control inline">
<option value="">Select Service..</option>
<option *ngFor="let serviceOption of serviceOptions" [ngValue]="serviceOption.serviceNumber">
{{serviceOption.serviceDescription}}
</option>
</select>
<button (click)="onAddService()">
Add
</button>
</div>
<div>
<button type="submit">
Save
</button>
</div>
</form>
親切的問候。
------ 打字稿代碼:
export class NewServiceComponent implements OnInit {
newServiceForm: FormGroup;
serviceOptions: IServiceArticle[] = [
{ 'id': 1, 'serviceNumber': 123456, serviceDescription: 'description 1' },
{ 'id': 2, 'serviceNumber': 456789, serviceDescription: 'description 2' },
{ 'id': 3, 'serviceNumber': 123456, serviceDescription: 'description 3' },
];
selectedServiceOption: IServiceArticle;
newArticle: IService;
constructor(private _fb: FormBuilder) {
}
createForm() {
this.newServiceForm = this._fb.group({
services: this._fb.array([]),
articleNumber: this._fb.control(null, Validators.required),
})
}
ngOnInit() {
this.createForm();
}
onAddService() {
const arrayControl = <FormArray>this.newServiceForm.controls['services'];
let newgroup = this._fb.group({
serviceNumber: this.selectedServiceOption.serviceNumber,
serviceDescription: this.selectedServiceOption.serviceDescription,
})
arrayControl.push(newgroup);
}
}
只是想知道'select',這可能意味着用戶可以一次又一次地選擇相同的值? – Alex
在這個時候它可以。驗證邏輯應該被更新以避免這種情況。對於我對角度的理解,目前這不是問題。 –
嘿,它的答案是怎麼回事?有幫助還是需要進一步的幫助? :) – Alex