如何实施?
我的子组件
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
one.
看看这个笨蛋:https://plnkr.co/edit/2SOdq7w3s8iDxBKbiLpU?p=preview https://plnkr.co/edit/2SOdq7w3s8iDxBKbiLpU?p=preview.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)