角度传递变量到其他页面

时间:2017-06-16 05:19:20

标签: angular

在我的角度项目中,假设我有以下设置:

主页:

html的:

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

组件页面:

.TS:

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文件中未定义。

如何更改代码,以便定义info中的main page变量?

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

  console.log(info);  //Currently undefined

};

3 个答案:

答案 0 :(得分: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 :(得分: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)
       }
    }
}

答案 2 :(得分: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;

}