[英]Angular 8 - FormBuilder.group is not preserving arrays
I'm trying to set a form group from a [key:string]:any
but it's not preserving the arrays, when the array has one position it is becoming a number, and when it has more than one I'm getting an error.我试图从[key:string]:any
设置一个表单组,但它不保留数组,当数组有一个位置时它变成一个数字,当它有一个以上时我收到错误.
// Example
let keyList = {
'TestArray' = [1],
'Name' = 'John'
};
let formGroup = this.formBuilder.group(keyList);
console.log(formGroup.get('TestArray').value); // 1 instead of [1]
To create array of value, you should create formArray要创建值数组,您应该创建 formArray
component.ts组件.ts
let keyList = {
'TestArray':this.formBuilder.array([[1]]),
'Name' : 'John'
};
let formGroup = this.formBuilder.group(keyList);
console.log(formGroup.get('TestArray').value);
'TestArray' = [1]
implies that you are creating formControl instead of formArray. 'TestArray' = [1]
表示您正在创建 formControl 而不是 formArray。 For creating formArray use formBuilder.array用于创建 formArray 使用formBuilder.array
const array = [1,2,3];
let keyList = {
'TestArray' = this.formBuilder.array(array),
'Name' = 'John'
};
Refer the example for creating different types of controls :-请参阅创建不同类型控件的示例:-
createForm() {
this.form = this.formBuilder.group({
'firstName': 'MyFirstName',
'lastName' : ['MyLastName'],
'contact': ['99999999999', [Validators.required]],
'agree': [true, Validators.requiredTrue],
'hobbies': this.formBuilder.array(['reading, cooking']),
'locations': [[], Validators.required],
});
}
try this:尝试这个:
let keyList = {
'TestArray' : new FormControl([1]),
'Name' : 'John'
};
let formGroup = this.formBuilder.group(keyList);
console.log(formGroup.get('TestArray').value);
output you will get is some thing like:你会得到的输出是这样的:
[1]
0: 1
length: 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.