2016-03-19 10 views
0

コンポーネントインスタンスのフィールドを変更します。例えば 、中test.component.tsは:コンシューマはコンストラクタパラメータをAngular 2でどのように供給しますか?

@Component({ 
    selector: 'test', 
}) 
export class TestComponent {  
    @Input() temp; 
    temp2; 
    constructor(arg) { 
     this.temp = arg; 
     this.temp2 = arg * 2; 
    } 
} 

私は、コンストラクタを使用して、TEMPとTEMP2の値を設定します。私は1つのアプローチのようなものをすることによって、入力プロパティを使用することです知っている:

<test [temp]='1'></test> 

しかし、これは構築時間後に行われ、TEMP2はそれに応じて変更されることはありません。コンシューマの視点からコンポーネントのコンストラクタ引数を指定すると、 "temp"と "temp2"の値は構築時に設定されます。

ありがとうございます!成分の実際の入力で

+0

が、何 'arg'されますか?あなたは恥を提供することはできますか? – micronyks

答えて

2

ためのngOnInitメソッドからのみ入手可能ですコンポーネントのライフサイクル:

@Component({ 
    selector: 'test', 
}) 
export class TestComponent {  
    @Input() temp; 

    ngOnInit() { 
     console.log(this.temp); 
    } 
} 

また、コンポーネントコンストラクターでは、依存関係注入によって提供されるパラメーターのみを使用できます。

したがって、コンポーネントライフサイクルのために一時プロパティにコンストラクタを使用することはできません。それはどのように利用できるかによって異なります。それが依存関係注入の場合は動作しますが、注入するものを指定するには@Injectデコレータを使用する必要があります。

あなたはまた、より多くの詳細については、この質問を見ている可能性があり:

0

sharedServcie.ts

import {Injectable} from 'angular2/core'; 

@Injectable() 
export class sharedService{ 
    test:string="Angular2"; 
} 

boot.ts

import {sharedService} from './sharedService'; 
... 
... 
bootstrap[App,[sharedService]] 

import {sharedService} from './sharedService'; 
@Component({ 
    selector: 'test', 
}) 
export class TestComponent {  
    temp; 
    constructor(sharedService:sharedService) { 
     this.temp = sharedService.test; 
     console.log(this.temp) //Angular2 
    } 
} 
+0

お返事ありがとうございます!サービスは良い考えですが、htmlで引数を指定することは可能です(例えば、または Angular2)。 – lys1030

+0

AFAIK '' 'temp'は' test' cmpで自由に使うことができます...注入する必要はありません。私はあなたの文脈を完全に理解していません... – micronyks

+0

temp(例えばtemp2 = temp * 2;)に関連付けられたtest cmpの別のインスタンスvar temp2がある場合、@Input()を使ってtempを変更しないでくださいtemp2の値したがって、私は建設中に議論を提供したいと思います。 – lys1030

0

私はanswer Thierry Templierはあなたの問題を説明したが、

は、あなたがコメントで言うと思う:

質問が更新されました鉱石は透明です。入力 の入力を使用すると、私はtempを変更することしかできませんが、temp2はそれに応じて を更新しません。

私はこれがあなたが達成したいと望むものであると願っています。

import {Input, Component} from 'angular2/core' 

    @Component({ 
     selector: 'my-test', 
     template: ` 
     <h1> arg value: {{ arg }} </h1> 
     <h1> temp value: {{ temp }} </h1> 
     <h1> temp1 value: {{ temp1 }} </h1> 
    ` 
    }) 

    export class test { 
     @Input() arg : number; 
     temp : number; 
     temp1: number; 

     constructor(){ 

     } 

     ngOnInit(){ 
     this.temp = this.arg; 
     this.temp1 = this.arg * 2; 
     } 

    } 

    @Component({ 
     selector: 'my-app', 
     directives: [test], 
     template: ` 
     <h2>Hello {{name}}</h2> 
     <my-test [arg]="1"></my-test> 
    ` 
    }) 
    export class App { 
     constructor() { 
     this.name = 'Angular2'; 
     } 
    } 

テストPlunker

関連する問題