Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReBuild/Re-render Angular2 component when property is changed

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

like image 456
MAHESH VALIYA VEETIL Avatar asked Jun 20 '26 12:06

MAHESH VALIYA VEETIL


1 Answers

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.

like image 87
Thierry Templier Avatar answered Jun 22 '26 02:06

Thierry Templier



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!