Steve Kim
Steve Kim

Reputation: 5611

Angular passing variable to other page

In my angular project, let say I have following setup:

Main Page:

.html:

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

Component page:

.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>

The idea is to use the myCard html template inside of the main page, which works just fine.

However somehow the info is undefined inside of .ts file.

How would I change the code so that info variable from the main page is defined?

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

  console.log(info);  //Currently undefined

};

Upvotes: 0

Views: 88

Answers (3)

rajeev
rajeev

Reputation: 64

please check example code, if possible please share your code if it does not help.

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;

}

Upvotes: 1

Amit Chigadani
Amit Chigadani

Reputation: 29785

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)
       }
    }
}

Upvotes: 1

Bharat Chauhan
Bharat Chauhan

Reputation: 3332

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

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

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

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

}

Upvotes: 1

Related Questions