2016-05-12 6 views
2

これを実装する方法?プロパティが変更されたときにRebuild/Angular2コンポーネントを再レンダリングします

私のサブコンポーネント

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

@Component({ 
selector: 'my-component', 
template: ` 
    <div>In child component - myAttr = {{ myAttr1 }}</div> 
` 
}) 
export class MyComponent { 
    @Input() myAttr: number; 
    myAttr1:number; 
ngOnInit() 
{ 
    this.myAttr1=this.myAttr*10; 
} 

} 

メインコンポーネント

import {Component} from 'angular2/core'; 
import {MyComponent} from './sub.component'; 

@Component({ 
selector: 'my-app', 
template: ` 
    <my-component 
     [(myAttr)]="myAttr" 
    ></my-component> 
    <button (click)="onClick()">Click</button> 
`, 
directives: [MyComponent] 
}) 
export class AppComponent { 
    myAttr: number = 1; 

    onClick() { 
    console.log('Click in the parent component'); 
    this.myAttr += 1; 
    } 
} 

私は、各クリックで値を更新する必要があります。直接的なアプローチがあるはず、それ以外Angular2チームは考えなければならない。この

答えて

2
myAttrがあなたのサブコンポーネントで更新されたときは、検出するngOnChangesを使用する必要があり

:これはmyAttr入力プロパティがあるときを検出することができます

@Component({ 
    selector: 'my-component', 
    template: ` 
    <div>In child component - myAttr = {{ myAttr1 }}</div> 
    ` 
}) 
export class MyComponent { 
    @Input() myAttr: number; 
    myAttr1:number; 
    ngOnInit() { 
    this.myAttr1=this.myAttr*10; 
    } 

    ngOnChanges() { // <------ 
    this.myAttr1=this.myAttr*10; 
    } 
} 

更新し、それに応じてmyAttr1を更新します。

このplunkr:https://plnkr.co/edit/2SOdq7w3s8iDxBKbiLpU?p=previewを参照してください。

+0

はい。見つけた。これは簡単な例であるため、これを達成することができます。 –

+0

プロパティに双方向バインディングオプションはありますか? –

+1

双方向バインディングの場合、 '@ Output'を接頭辞:Changeという名前で追加する必要があります。たとえば、次のようになります。 '@Output()myAttrChange:EventEmitter = new EventEmitter();' 'emit'メソッドを使ってイベントをトリガする必要があります。これにより、次の構文を使用できます: '[(myAttr)] =" myAttr "'。 –

関連する問題