2017-06-16 59 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; 

}