2016-04-19 9 views
0

子要素としてプレイリストコンポーネントがあり、Arrayのオブジェクトである入力 'playlist'に親パスがあります。アクセス方法Angular2の親コンポーネントから渡された入力データ

playList: { 
    headerPlaylists: Array<any>, 
    bodyPlaylists: Array<any> 
    } = { 
    headerPlaylists: [], 
    bodyPlaylists: [] 
    } 

子コンポーネント

@Component({ 
    selector: 'playlist', 
    styleUrls: ['app/channel/playlist/playlist.css'], 
    templateUrl: 'app/channel/playlist/playlist.html', 
    directives: [VideoItemComponent], 
    inputs: ['playlist'] 
}) 

以下のように私の質問は、私のクラスでは、どのように私はそれから渡された入力へのアクセスを得るのですか、単に(プレイリストをCONSOLE.LOG、たとえば、親コンポーネントですされます)、それを行う方法はありますか?

export class PlaylistComponent { 

    constructor() { 

    } 
} 

答えて

2

ティエリーが正しいw.r.t.ですライフサイクル全体にわたる入力の可用性ですが、inputsではなくフィールドで@Input()を使用すると、これがどのように機能するかがはっきりします。大きく、このため@Input()を介して入力を指定がng2 style guideに従って入力を使用よりも好ましい

@Component({ 
    selector: 'playlist', 
    styleUrls: ['app/channel/playlist/playlist.css'], 
    templateUrl: 'app/channel/playlist/playlist.html', 
    directives: [VideoItemComponent], 
// inputs: ['playlist'] // would be redundant 
}) 
class PlaylistComponent implements OnInit { 
    @Input() playlist: YourPlaylistType; // i.e. the data structure you posted 

    ngOnInit(){ 
    // use this.playlist 
    } 
} 

注意。

1

playlistプロパティはコンポーネントのngOnInitフックメソッド内で利用できるようになります。コンストラクタで

export class PlaylistComponent { 
    playlist: any; // or a specify type instead of any 

    constructor() { 
    console.log(this.playlist); // is null 
    } 

    ngOnInit() { 
    console.log(this.playlist); // is set 
    } 
} 

、プロパティがまだ設定されていません。

詳細については、ライフサイクルフックについてはこちらのページを参照してください。

+1

クラスに 'playlist'プロパティがある必要があります。これはコンパイルされません。 – drewmoore

+0

あなたは正しいです。私はプロパティを表示するときに焦点を当てていたので、プロパティの宣言を忘れてしまった。私は自分の答えを更新しました。ありがとう! –

関連する問題