2017-12-05 4 views
0

親と子の2つのコンポーネントを作成しました。@Input()をコンストラクタ内で動作させることができません

import { Component, OnInit } from '@angular/core'; 
import { CoreService } from 'app/core.service'; 
import { Application } from 'app/models/application.model'; 

@Component({ 
    selector: 'app-applicationbrowser', 
    templateUrl: './applicationbrowser.component.html', 
    styleUrls: ['./applicationbrowser.component.css'], 
    providers: [CoreService] 
}) 
export class ApplicationbrowserComponent { 
    applications: Application[] = [ 
    new Application(1, false, "beef"), 
    new Application(2, false, "teef"), 
    new Application(3, false, "feef") 
    ]; 
    constructor() { 

    } 
} 

をし、そのテンプレートに子コンポーネントを使用しています:

親は、メンバ変数と呼ばれるアプリケーションを持ってい

<div> 
    <app-resourceitem *ngFor="let item of applications" [item]="item"></app-resourceitem> 
</div> 

私はこれが私のアプリケーション変数にアプリケーションごとに呼び出されることを想定しました。

しかし、子コンポーネントは今まで「未定義」アイテムの変数があります。

@Input() 
    item: any; 
    constructor() { 
    debugger; 
    console.log(this.item); //item is always undefined.... 
    } 

は私が間違って何をやっているの?

答えて

1

@InputデータはngOnInitで利用でき、コンストラクタではありません。

@Component({ 
    ... 
}) 
export class SomeChildComponent implements OnInit { 
    @Input() item: any; 
    constructor(){} 

    ngOnInit() { 
    console.log(this.item); 
    } 
} 
+0

[OK]を、として変更し、私はコンストラクタでふざける二時間を費やして、私はそれが働いていた甘い赤ん坊のイエスによって十分ティ – Jay

+1

を試してみましょう。時にはその単純なもの... – Jay

0

はngOnInitライフサイクルフックでそれを行う、コンストラクタで@Input()にアクセスしようとしないでください。コンストラクタはAngularアプリケーションのライフサイクルとは関係ありません。あなたのコードが

@Component({ 
}) 
export class SomeChildComponent implements OnInit { 
    @Input() item: any; 
    constructor(){} 
    ngOnInit() { 
    console.log(this.item); 
    } 
} 

DEMO WITH STACKBLITZ

関連する問題