简体   繁体   中英

Re-render Angular2 component when property is changed

Lets say I have the following scenario:

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

  onClick() {
      this.myAttr += 1;
  }
}

so when the button is clicked I want to rerender the component so the new value is populated on the underlying components. I have tried the two way binding as well, but does not make much sense in this case as it is a one way binding. So the question is how do I trigger update?

Thanks!

In fact, the value is automatically updated into your sub component if you use interpolation (like you do) with an input and when updated in the parent component.

Here is the way to define the sub component:

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

@Component({
  selector: 'my-component',
  template: `
    <div>{{myAttr}}</div>
  `
})
export class MyComponent {
  @Input()
  myAttr: number;

}

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

You don't need to trigger anything. The update happens automatically because of the way Angular change detection works.

Angular monkey-patches all asynchronous events that are defined within the Angular "zone" (such as your (click) event binding), so after your onClick() event handler finishes, Angular will automatically run change detection.

Change detection will notice that myAttr is bound to an input property of MyComponent and it will automatically propagate the new value to the child component. Change detection will also notice (if we use Thierry's example) that property myAttr is bound to a div and it will automatically propagate the new value to the div 's textContent property. Angular change detection finishes, then the browser notices the DOM change and updates what you see on the screen.

You are right about this, however there is one more thing - which event should be used to detect this change in the child component to perform certain logic. I can see that the ngAfterContentCheck event is fired for example, however it fires multiple times and I cannot seem to figure out the reason.

And one more thing - can I push update from the child component. So for example the my-app component that controls the myAttr will be updated when something changes in the child component (from user input or something like that). I am thinking React way here, so I am not sure this is the right approach.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM