2016-12-17 74 views
4

我正在查看示例Angular 2项目并插入了一些代码以尝试从传递给嵌套子组件的电影对象中提取值。Angular2新手将数据从父项传递到子项

在父代码中,我有以下几点:

<div class="col-sm-6 col-md-4 col-lg-3 col-xs-6" *ngFor="let movie of movies; let i = index;"> 
    <movie-card [movie]="movie"></movie-card> 
</div> 

在我的电影,card.component.ts文件我有这样的代码:

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

@Component({ 
    selector: 'movie-card', 
    templateUrl: './movie-card.component.html', 
    styleUrls: ['./movie-card.component.css'] 
}) 
export class MovieCardComponent { 

    @Input() 
    movie: Object; 

    constructor() { 

    console.log('movie : ' + this.movie); 
    } 

} 

输出到我的浏览器控制台:

20 movie : undefined movie-card.component.ts:15 

但在电影card.component.html

{{movie.Name}} 

html将输出电影名称。

我想发送movie.Name值到我这样的服务。

_anatomyService.getImage(this.movie.Name); 

但是,电影的价值是未定义的。我不了解什么?

预先感谢您。

回答

2

您的电影card.component.ts应该是这样的。

import { Component, Input, OnInit } from '@angular/core'; <-- add OnInit 

    @Component({ 
     selector: 'movie-card', 
     templateUrl: './movie-card.component.html', 
     styleUrls: ['./movie-card.component.css'] 
    }) 
    export class MovieCardComponent { 

     @Input() 
     movie: Object; 

     constructor() { } 

    ngOnInit() {  <-- your this.movie should be in ngOnInit lifecycle hook 
     console.log('movie : ' + this.movie); 
     } 

    } 

检查此链接了解更多的生命周期挂钩http://learnangular2.com/lifecycle/

3

您可以使用一套关于你的价值

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

@Component({ 
    selector: 'movie-card', 
    templateUrl: './movie-card.component.html', 
    styleUrls: ['./movie-card.component.css'] 
}) 
export class MovieCardComponent { 

    @Input() 
    set movie(movie: Object){ 
    console.log(movie); 
    //asign it to a value or do something with it 
    } 

} 
相关问题