本文介绍了更改属性后重新构建/重新渲染Angular2组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何说明这一点?
我的子组件
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团队应该考虑一下
I need to update the value in each click. There should be a direct approach , else Angular2 team should think about this
推荐答案
您应该使用ngOnChanges来检测子组件中myAttr
的更新时间:
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;
}
}
这可以检测到myAttr
输入属性何时更新,并相应地更新myAttr1
一个.
This allows to detect when the myAttr
input property is updated and update accordingly the myAttr1
one.
查看此插件: https://plnkr.co/edit/2SOdq7w3s8iDxBKbiLpU?p=preview .
这篇关于更改属性后重新构建/重新渲染Angular2组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!