如何实现?
我的子组件
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
一个。
查看此插件:https://plnkr.co/edit/2SOdq7w3s8iDxBKbiLpU?p=preview .
关于properties - 属性更改时重新构建/重新渲染 Angular2 组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37180023/