ngOnChanges在输入属性更改时不触发 [英] ngOnChanges not firing when input property changed
本文介绍了ngOnChanges在输入属性更改时不触发的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在angular2中更改零部件属性时,可以通过编程方式触发角度变化检测吗?
Can you programatically trigger angular's change detection when mutating a component property in angular2?
@Component({
selector: 'my-component',
})
class MyComponent implements OnChanges {
@Input() message: string;
ngOnChanges(changeRecord) {
for (var change in changeRecord) {
console.log('changed: ' + change);
}
}
doSomething() {
// I want ngOnChanges to be called some time after I set the
// message. Currently it is only called if the host element
// changes the value of [message] on the element.
this.message = 'some important stuff';
}
}
推荐答案
尝试手动调用更改检测或花费大量时间解决此问题,这是一种过大的方法,为什么不创建一个函数来处理所需的突变并调用在ngOnChanges
和doSomething
中都可以吗?像这样:
Trying to manually call change detection or spent a lot of time on a workaround for this is way overkilling, why not creating a function to handle the desired mutation and call it in both ngOnChanges
and doSomething
? something like:
@Component({
selector: 'my-component',
})
class MyComponent implements OnChanges {
@Input() message: string;
viewMessage: string;
ngOnChanges(changes: { [propertyName: string]: SimpleChange }) {
for (let propName in changes) {
if (propName === 'message') {
this.updateView(this.message);
}
}
}
doSomething() {
this.viewMessage = 'some important stuff';
}
updateView(message: string) {
this.viewMessage = message;
}
}
所以viewMessage
将是您将要使用和控制模板的属性.
So viewMessage
will be the attribute you'll be using and controlling the template.
这篇关于ngOnChanges在输入属性更改时不触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文