When creating a component (let's call it A) with the @input decorator to retrieve values from the selector, keep in mind that this component will generate text fields based on the input values specified in the selector. Component A is then utilized in another component (referred to as B).
Component B contains the selector for Component A and also includes a button. Upon clicking the button, a function (named GetData) is triggered.
Within the GetData function, there is a call to the getValues function of Component A by instantiating an object for Component A. However, when clicking on the GetData function, the getValues function of the component throws a console error stating "cannot read property 'length' of undefined."
Please provide assistance in resolving this issue. Thank you.
Component A
import { Component, Input, OnInit, ViewChildren } from '@angular/core';
@Component({
selector: 'my-comp',
templateUrl: '<form #f="ngForm">
<div *ngFor="let iter of arr(num).fill(1);let i=index">
<input type="text" name="textValue{{i}}" ngModel #textValue="ngModel" [id]="'textValue' + i">
</div>
</form>'
})
export class MyCompComponent {
@ViewChildren('textValue') inputs;
public myData:any=[];
@Input('iterNumber') iterNum: number;
arr = Array;
num: number;
ngOnInit() {
this.num = this.iterNum;
}
getValues() {
debugger
for(var i=0;i<this.inputs.length;i++){
this.myData.push(this.inputs._results[i].viewModel)
}
console.log(this.myData)
}
}
Component B
import { MyCompComponent } from '../my-comp/my-comp.component';
import { Component, Input,Directive } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: '<my-comp [iterNumber]=3></my-comp>
<button type="button" (click)="getValues()">GetValues</button>'
})
export class AppComponent {
public getValueList:any;
constructor(public cmpnt:MyCompComponent){
}
getData(){
this.cmpnt.getValues();
}
}
Error in Console
EXCEPTION:
Error in ./AppComponent class AppComponent - inline template:1:0 caused by: Cannot read property 'length' of undefined
ORIGINAL EXCEPTION:
Cannot read property 'length' of undefined