2016-12-17 76 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 
    } 

} 
相關問題