ReBuild/Re-render Angular2 component when property is changed

江枫思渺然 提交于 2019-12-12 15:40:18

问题


How to Implment this?

My SubComponent

 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;
 }

}

Main Component

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;
  }
}

I need to update the value in each click. There should be a direct approach , else Angular2 team should think about this


回答1:


You should use ngOnChanges to detect when myAttr is updated in your sub component:

@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;
  }
}

This allows to detect when the myAttr input property is updated and update accordingly the myAttr1 one.

See this plunkr: https://plnkr.co/edit/2SOdq7w3s8iDxBKbiLpU?p=preview.



来源:https://stackoverflow.com/questions/37180023/rebuild-re-render-angular2-component-when-property-is-changed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!