2017-08-02 167 views
-2

我正在使用for循环,并希望使用@Input事件发送器将数据发送到其他组件。 但问题是我只接收组件模板中的最后一个值。如何从for循环发送数据

请指教,需要帮助。

父组件TS

import { Component, OnInit, Input, ViewEncapsulation } from '@angular/core'; 

@Component(
    { 
    selector  : 'parent-component', 
    templateUrl : './parent.component.html', 
    } 
) 
export class ParentComponent implements OnInit { 
    public data; 

    constructor() { 
    } 

    getData(){ 
    for (let i = 1; i <= i; i++) {   
     this.data = i; 
    } 
    } 
} 

父组件模板

<child-component [data]="data"></child-component> 

辅元件TS

import { Component, OnInit, ViewChild, Input, Output, EventEmitter, OnChanges, SimpleChanges } from '@angular/core'; 
@Component({ 
    selector: 'child-component', 
    templateUrl: './child-component.html' 
}) 

export class ChildComponent implements OnInit, OnChanges { 
@Input() 
    data; 

    constructor() { } 
    ngOnChanges(changes: SimpleChanges) { 
    // i am receiving a value 1,2, 3...10 
    } 
} 

子组件模板

  <div>{{data}}</div> 

我在父组件中使用循环来获取子组件中的数据,我必须在未在子组件中反映的子组件中显示子组件。 请建议。

+0

请告诉我们您已经尝试了什么。 – Jordumus

+0

你现在怎么发送它? –

+0

使用父组件中的'@ Input'更新for循环中的值并在子组件中进行接收。在模板'{{data}}'中,这个数据模板只显示10,即循环的最后一个值。但是在ngOnChanges()钩子中,我可以看到更新后的值 – Vaibhav

回答

0

输入绑定只能看到它们绑定的数据的值当前。如果你能够减缓循环,你会看到界限值经过1,2,3等,但一次只能得到一个值。

如果您希望它从循环中获取所有值,则需要使用数组或类似的东西。例如:

export class ParentComponent implements OnInit { 
    public data = []; 

    constructor() { 
    } 

    getData(){ 
    // I assume this was supposed to be 10, not i, or else you get an infinite loop 
    for (let i = 1; i <= 10; i++) {   
     this.data.push(i); 
    } 
    } 
}