2017-08-02 63 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); 
    } 
    } 
}