【问题标题】:Angular 2, gives cannot read property 'length' of undefined while calling a function from another componentsAngular 2,在从其他组件调用函数时无法读取未定义的属性“长度”
【发布时间】:2017-08-08 15:26:01
【问题描述】:

我用@input 装饰器创建了一个组件(比如说A)来从选择器中获取值。该组件将创建 基于选择器中给定的@input 值的文本字段。 A 组件正在另一个组件中使用(比方说 B)
B 组件具有 A 组件选择器和一个按钮。单击按钮时,我正在调用一个函数(比如说GetData)。
GetData 函数内部,我通过为A 组件创建对象来从A 组件调用该函数(比如说getValues)。 单击GetData 函数时,它会从组件中调用getValues 函数,该函数会引发控制台错误,因为无法读取未定义的属性“长度” 请帮我解决这个问题提前谢谢

组件 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)
    }
}

组件 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();
  }
}

控制台出错

例外:

./AppComponent 类 AppComponent 中的错误 - 内联模板:1:0 原因:无法读取未定义的属性“长度”

原始异常:

无法读取未定义的属性“长度”

【问题讨论】:

标签: angular typescript


【解决方案1】:

组件不是可注入的provider。它不能注入到另一个组件中。

这里去掉参数即可:

 constructor(public cmpnt:MyCompComponent){

  }

并使用视图子级。

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

  public getValueList:any;

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

【讨论】:

  • 没有任何效果,但之前的长度错误没有出现,但我得到了无法读取未定义的属性“推送”,有什么想法
  • 你的 ViewChild 给了我一些想法,现在它在对代码进行一些修改后可以工作了,谢谢
【解决方案2】:

您的 html 代码中有一些错误,例如您在 input 中使用了多个 name 属性。

请看https://codepen.io/souldreamer/pen/QydMNG他们在哪里做了类似的东西(这不是我写的)。

希望这会有所帮助。

【讨论】:

  • 现在检查我已经编辑了问题,你的代码笔不工作请检查它
猜你喜欢
  • 2016-09-25
  • 2020-07-05
  • 1970-01-01
  • 1970-01-01
  • 2014-11-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-11
相关资源
最近更新 更多