简体   繁体   English

表单中的Angular2访问值

[英]Angular2 access value in Form

I have a problem getting an id from my form. 我在从表单获取ID时遇到问题。

this.myForm looks like this @Input() public myForm: FormGroup; this.myForm看起来像这样@Input()public myForm:FormGroup;

it is a input from another .ts file 它是另一个.ts文件的输入

this is the structure of the form: 这是表格的结构:
myForm myForm会
- firstname - 名字
- lastname - 姓
- Email -电子邮件
--Tags (FormArray) -标签(FormArray)
---id (FormGroup) --- 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: 我想访问id并用一个用户的所有标签填充this.selectedTagList,这就是我想要做的:

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: 如果我console.log(this.myForm)我得到这个结构:
this.myForm

console.log(control.controls), 'controls' from the code above: console.log(control.controls),上面代码中的“控件”:
在此处输入图片说明

but when i do console.log(control.controls.length) i get 0. Or when i do console.log(control.controls[0]) i get undefined. 但是当我执行console.log(control.controls.length)时,我将获得0。或者当我执行console.log(control.controls [0])时,我将变得不确定。

I have no idea where the FormGroup objects went or why it says Array[0] with 4 FormGroup objects in it. 我不知道FormGroup对象去了哪里,或者为什么它说其中有4个FormGroup对象的Array [0]。

试试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. 在JavaScript中,数组使用编号索引。 In JavaScript, objects use named indexes.Where names indexes is the same as associative array. 在JavaScript中,对象使用命名索引。名称索引与关联数组相同。

For more info see: https://www.w3schools.com/js/js_arrays.asp 有关更多信息,请参见: https : //www.w3schools.com/js/js_arrays.asp

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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