ReBuild/Re-render 更改 属性 时的 Angular2 组件

ReBuild/Re-render Angular2 component when property is changed

如何实施?

我的子组件

 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 团队应该考虑这个

您应该使用 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;
  }
}

这允许检测 myAttr 输入 属性 何时更新并相应地更新 myAttr1 输入。

看到这个 plunkr:https://plnkr.co/edit/2SOdq7w3s8iDxBKbiLpU?p=preview