你是否可以在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中调用它?就像是:
原文链接:https://www.f2er.com/angularjs/141101.html@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将是您将使用的属性并控制模板.