我不知道在我的情況下如何能管理我的表單。想象一下,一個有7個初始值的表格:
- 姓名
- 公司
- 電子郵件
- 地址
- 產品(可重復)
- 序列號(可重復) 。
- 退貨說明 。
有一個按鈕可以創建一個新的產品和序列號輸入欄位組件的實體(以防有更多的產品)。這就意味著我需要創建另一個組件來制作一個嵌套的表單。我遇到的問題是,我不知道如何管理這個問題。
我目前是這樣記錄我的數值的:
console.log(this. parentForm.controls.name.value)。)
console.log(this. parentForm.controls.company.value)。)
console.log(this。 parentForm.controls.email.value)。)
console.log(this. parentForm.controls.address.value)。)
console.log(this. parentForm.controls.returnInstructions.value)。)
但我仍在試圖找出如何存盤我的產品和SN值(以及有可能洗掉它們)。我正在考慮將它們存盤在一個物件陣列中,該陣列將被發送到父組件(有主表單的那個)。這個陣列看起來像:{Object1: product1, SN1, Object2: product2, SN2...},但我不知道如何建立它。
uj5u.com熱心網友回復:
這就是表單陣列的完美用例。下面的驗證只是一個例子。
。
get products()。FormArray {
return this.fooForm。 get('products') as FormArray。
}
constructor(private fb: FormBuilder) { }
ngOnInit()。void {
this.fooForm = this.fb.group({
name: [''/span>, [Validators. required, Validators.minLength(3) ]。
company: [''/span>, [Validators. required, Validators.maxLength(50) ]。
email: [''/span>, [Validators. required, Validators.email]】。]
address: '',
products: this.fb.array([this.buildProduct() ])
});
}
buildProduct()。FormGroup {
return this.fb.group({
name: ['', Validators.required] 。
serialNumber: ['', Validators.required] 。
});
}
然后像這樣移除:
removeProduct(index: number)。void {
this.products.removeAt(index)。
}
像這樣添加產品:
addProduct(): void {
this.products.push(this.buildProduct() )。)
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/323547.html
標籤:
