Sum*_*wal 26 typescript angular2-forms angular
我已经准备好了使用angular2/forms提供的ReactiveForms.此表单有一个表单数组产品:
this.checkoutFormGroup = this.fb.group({
selectedNominee: ['', Validators.required],
selectedBank: ['', Validators.required],
products: productFormGroupArray
});
Run Code Online (Sandbox Code Playgroud)
productFormGroupArray是一个FormGroup Objects数组.我使用以下方法获取控件,即FormArray对象:
this.checkoutFormGroup.get('products')
Run Code Online (Sandbox Code Playgroud)
我试图在索引的product数组中获取元素i
.如何在不循环数组的情况下完成这项工作?
编辑:
我尝试使用at(index)方法:
this.checkoutFormGroup.get('products').at(index)
Run Code Online (Sandbox Code Playgroud)
但这会产生一个错误:
Property 'at' does not exist on type 'AbstractControl'.
Run Code Online (Sandbox Code Playgroud)
编辑2: 从服务器收到checkoutData和fund.
this.checkoutData.products.forEach(product => {
this.fundFormGroupArray.push(this.fb.group({
investmentAmount: [this.fund.minInvestment, Validators.required],
selectedSubOption: ['', Validators.required],
}))
});
Run Code Online (Sandbox Code Playgroud)
Rad*_*ler 43
只需将该控件转换为数组
var arrayControl = this.checkoutFormGroup.get('products') as FormArray;
Run Code Online (Sandbox Code Playgroud)
它的所有功能都在那里
var item = arrayControl.at(index);
Run Code Online (Sandbox Code Playgroud)
Typ*_*hon 11
虽然在使用该at()
方法之前将 AbstractControl 转换为 FormArray是一种方法,但我还没有看到任何人指出您也可以使用该get()
方法来执行它,该方法不需要转换。
根据Angular 的文档,签名get()
是:
get(path: string | (string | number)[]): AbstractControl | null
这意味着您还可以使用它访问 FormArray 的控件。
例子 :
const formGroup = new FormGroup({
list: new FormArray([
new FormControl('first'),
new FormControl('second'),
]),
});
const firstValue = formGroup.get('list.0').value; // Returns 'first'
const secondValue = formGroup.get('list.1').value; // Returns 'second'
Run Code Online (Sandbox Code Playgroud)
这非常有用,当您想在 HTML 中绑定 FormControl 时,您不能在其中强制转换任何内容:
<input [formControl]="formGroup.get('list.0')">
Run Code Online (Sandbox Code Playgroud)
以下是这样做的方法的摘要:
const firstControl = listControl.get('list.0');
Run Code Online (Sandbox Code Playgroud)
const firstControl = listControl.get(['list', 0]);
Run Code Online (Sandbox Code Playgroud)
const firstControl = listControl.get('list').get('0'); // You need a string and not a number
Run Code Online (Sandbox Code Playgroud)
const listControl = formGroup.get('list') as FormArray;
const firstControl = listControl.at(0);
Run Code Online (Sandbox Code Playgroud)
一个衬板作为当前接受答案的一种选择
var item = (<FormArray>this.checkoutFormGroup.get('products')).at(index);
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
27006 次 |
最近记录: |