2017-06-16 62 views
0
其他頁面

在我的角度項目,讓說,我有如下設置:角傳球變量

主頁:

的.html:

<div class="main component" *ngFor="let item of items;"> 
    <my-card [info]="item"></my-card>    
</div> 

組件頁:

。:

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

@Component({ 
    selector: 'my-card', 
    templateUrl: 'myCard.html' 
}) 

export class myCard{ 
    @Input() info: Array<any>;  

} 

的.html:

<div class="subComponent"> {{info}}</div> 

的想法是使用主網頁,其工作只是正常的內部myCard HTML模板。

但不知何故info.ts文件內部未定義的。

我該如何更改代碼,以便定義main pageinfo變量?

export class myCard{ 
    @Input() info: Array<any>; 

    console.log(info); //Currently undefined 

}; 
+0

item不是數組,我認爲;所以這應該是@Input()info:any; –

+1

您是否嘗試過使用'ngOnInit'鉤子? – yurzui

+0

要明確,'console.log'語句應該放在'ngOnInit'裏面 – Skeptor

回答

1
import { Component, Input, SimpleChanges } from '@angular/core'; 

@Component({ 
    selector: 'my-card', 
    templateUrl: 'myCard.html' 
}) 

export class myCard implements OnInit, OnChanges { 
    @Input() info: Array<any>; 

    ngOnInit() { 
     console.log(this.info) 
    } 
    ngOnChanges(changes : SimpleChanges) { 
     if(typeof changes['info'] !== 'undefined'){ 
     console.log(this.info) 
     } 
    } 
} 
1
import { Component, Input } from '@angular/core'; 

@Component({ 
    selector: 'my-card', 
    templateUrl: 'myCard.html' 
}) 

export class myCard{ 
    @Input() info: any; 

    ngOnChanges() { 
    console.log(this.info); 
    } 

} 
1

example code,如果可能的話,請分享你的代碼,如果它不能幫助。

import { Component } from '@angular/core'; 

import { ChildComponent } from './child.component'; 


@Component({ 
    selector: 'my-app', 
    template: ` 
    <h1>{{title}}</h1> 
    <div *ngFor="let name of names"> 
    <app-child [name]="name"></app-child> 
    </div> 
    ` 
}) 
export class AppComponent { 
    title = 'hello'; 

    names:string[]=[]; 

    constructor(){ 

    this.names=['raj','honey','kinshuk']; 

    } 

} 

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

@Component({ 
    selector: 'app-child', 
    templateUrl: './child.template.html' 
}) 
export class ChildComponent{ 

    @Input() name; 

}