简体   繁体   中英

Angular2 access value in Form

I have a problem getting an id from my form.

this.myForm looks like this @Input() public myForm: FormGroup;

it is a input from another .ts file

this is the structure of the form:
myForm
- firstname
- lastname
- Email
--Tags (FormArray)
---id (FormGroup)

I want to get access to the id and fill this.selectedTagList with all the tags from one user and this is what i'm trying to do:

const control: FormArray = <FormArray>this.myForm.controls[ 'tags' ];
control.controls.forEach(tag=> {
this.selectedTagList.push(this.tagList.find(tag.value.id));
});

if i console.log(this.myForm) i get this structure:
this.myForm

console.log(control.controls), 'controls' from the code above:
在此处输入图片说明

but when i do console.log(control.controls.length) i get 0. Or when i do console.log(control.controls[0]) i get undefined.

I have no idea where the FormGroup objects went or why it says Array[0] with 4 FormGroup objects in it.

试试console.log(this.myForm.controls ['id']);

Try the same as John said, what you have is not a number indexed array, but you have a object with named indexes (like associative array).

In JavaScript, arrays use numbered indexes. In JavaScript, objects use named indexes.Where names indexes is the same as associative array.

For more info see: https://www.w3schools.com/js/js_arrays.asp

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM