When using Angular 2, an error may occur where you receive a message stating that you cannot read the property 'length' of undefined while attempting to call

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

Answer №1

A component is never considered an injectable provider. It does not have the ability to be injected into another component.

To resolve this, simply delete the parameter shown below:

 constructor(public cmpnt:MyCompComponent){

  }

Instead, utilize view child like so:

export class AppComponent  {
  @ViewChild(MyCompComponent)
  public cmpt:any;

  public getValueList:any;

 //..
    getData(){
    this.cmpnt.getValues();
  }

Answer №2

Your HTML code contains a few errors, such as using multiple name attributes within your input elements.

You can refer to this CodePen example for guidance: https://codepen.io/souldreamer/pen/QydMNG (note that I did not create this).

I hope this information is helpful to you.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Collaborate and reuse Typescript code across various Node projects

Imagine we have a project structured like this: webapps ProjectA SomeClass.ts Package.json ProjectB SomeClass.ts Package.json Common LoggingClass.ts Package.json The Common "LoggingClass" needs to import a module from NPM. Let's say that ...

Tips for disentangling code from types in Typescript

Instead of intertwining code and types like the example below: const compar8 : boolean | error = (action: string, n: number) => { switch(action) { case 'greater': return n > 8; case 'less': ...

What distinguishes display:none from *ngIf = 'false'?

The visibility:hidden property in CSS hides an element without changing its position or affecting the layout of other elements on the page. On the other hand, setting ngIf = 'false' in Angular removes the element from the DOM entirely, effectivel ...

The reload button retains functionality while being present within an Angular2 form, allowing for a seamless user experience. The

After some observation, I have realized that when a button is placed inside a form but has no connection or function related to the form, such as a back or cancel button, it unexpectedly reloads the entire page. For instance, let's consider having ...

Testing reactive streams with marble diagrams and functions

Upon returning an object from the Observable, one of its properties is a function. Even after assigning an empty function and emitting the object, the expectation using toBeObservable fails due to a non-deep match. For testing purposes, I am utilizing r ...

Unable to set value using React Hook Form for Material-UI Autocomplete is not functioning

Currently, I am in the process of constructing a form using React-Hook-Form paired with Material-UI. To ensure seamless integration, each Material-UI form component is encapsulated within a react-hook-form Controller component. One interesting feature I a ...

The collaboration feature in Angular is not functioning properly

In my application, I have two modules aside from the main module: - The Global.module, which contains shared modules; - The Pages.modules, which includes my pages. My goal is to make the modules in Global.module accessible to Pages.modules. However, I enc ...

Troubleshooting asynchronous problems with rxjs chaining within ngrx effects

@Effect({ dispatch: false }) public setJwtDataParcoursPage = this.actions$.pipe( ofType(INIT_FORM_SUCCESS_ACTION), map((action: InitFormSuccessAction) => action.payload), withLatestFrom(this.store.select(this._apiHeadersSelector.getJwt) as Observa ...

Revamp the button's visual presentation when it is in an active state

Currently, I'm facing a challenge with altering the visual appearance of a button. Specifically, I want to make it resemble an arrow protruding from it, indicating that it is the active button. The button in question is enclosed within a card componen ...

The type of 'data' is assumed to be 'any[]' without being explicitly stated

I am encountering several type errors in the function below, and as a newcomer to Typescript, I'm unsure about how to fix them. private fetchFromUrl = () => { var data = [] fetch(`${process.env.PUBLIC_URL}/tempData/monthly.csv`) .t ...

Showcasing diverse content with an Angular Dropdown Menu

I'm currently developing an angular application, and I've encountered a difficulty in displaying the user's selection from a dropdown menu. To elaborate, when a user selects a state like Texas, I want to show information such as the period, ...

Angular Typescript error: Trying to assign a value to 'someProperty' property of an undefined object

Within my Article class, I have a property called Image which is structured like this: export class Article { public image:Image; public images: Image[]; } If I decide to comment out this.article.image = new Image(); in the following way: constru ...

Error in MatSort implementation - Argument cannot be assigned

I'm having trouble figuring out how to implement the Mat-Sort functionality from Angular Material. When I try to declare my variable dataSource, I get the following error: Argument of type 'Observable' is not assignable to parameter of type ...

ng-pattern is not throwing any errors

After spending hours on this issue, I realized it was time to seek help here. I have been struggling with setting up an input field that displays a specific message when someone tries to type in a number. My extensive research brought me to ng-pattern as ...

Deconstructing Angular 2 Custom Pipes

As I delve deeper into learning Angular 2, my recent endeavor involves creating a custom pipe to filter results in my gallery by category. Unfortunately, the resources I've been referring to lack detailed explanations on how custom pipes actually work ...

Navigating JSON Objects in Ionic 2

Example of my JSON array structure [{ label: "Interests", datatype: "check", lookupname: "null", order: "05", options: [ 0:{id: "01", value: "Photography"} 1:{id: "0 ...

When using string as a primitive type in Vue 3, what distinguishes the usage of PropType in props from not using it?

The documentation explains how Vue does runtime validation on props with defined types. To enable TypeScript to recognize these types, constructors are cast with PropType. The code example in the documentation uses success: { type: String }, whereas it c ...

Creating an object instance in Angular 2 using TypeScript

Looking for guidance on creating a new instance in TypeScript. I seem to have everything set up correctly, but encountering an issue. export class User implements IUser { public id: number; public username: string; public firstname: string; ...

What is the process for incorporating buttons into an Angular mat-table?

I have successfully utilized Angular mat-table to showcase data retrieved from a database: view the image description here <table mat-table [dataSource]="UserDataSourceFilters" class="mat-elevation-z1 mt-5"> <ng-co ...

Show pictures stored in S3

I currently have an Amazon AWS S3 Bucket where I store images. Each object in the bucket has its own link, but when I try to open it in a browser, the image downloads instead of displaying directly on the site. This makes it challenging to view the images ...