问题
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