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.
// 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
component.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. For creating formArray use 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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.