【发布时间】:2016-04-06 08:12:38
【问题描述】:
当改变 angular2 中的组件属性时,您能否以编程方式触发 Angular 的更改检测?
@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';
}
}
【问题讨论】:
-
要手动运行更改检测,请尝试使用 ApplicationRef.tick()。但是,我不相信 ngOnChanges() 会被调用,因为主机属性没有改变。为什么要更改作为输入属性的子组件中的子属性?
-
上面的代码不是实际代码,我只是用它来演示问题。我的真实代码是一个单元测试,我已经使用
TestComponentBuilder获得了组件的一个实例。我希望单元测试代码修改message属性的值,并检查ngOnChanges中的代码是否发出了事件。但是经过几个小时的挠头后,我想不出任何方法来实现这一点。我也试过修改DebugElement上的nativeElement无效。 -
我一直在寻找像
ComponentFixture.modifyHostBinding(property: string, newValue: any)这样的方法,或者类似的方法,但似乎没有类似的方法,所以我提出了一个更通用的问题。 -
你得到答案了吗?
-
您在这里要做的是创建一个虚拟主机组件,如
TestHostComponent,它将按照规范绑定message属性。然后在您的测试中使用 fixture.detectChanges() 检查对message属性的更改。见相关:stackoverflow.com/questions/37408801/…
标签: angular