为什么detectChanges()之后复选框选中的属性没有更改 [英] Why checkbox checked property doesn't change after detectChanges()
本文介绍了为什么detectChanges()之后复选框选中的属性没有更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我尝试通过更改模型来更改复选框选中的属性,但是它不起作用.我无法理解这种行为.
I try to change checkbox checked property by changing model but it doesn't work. I cannot understand this behavior.
模板:
<input type="checkbox" [(ngModel)]="model"/>
测试代码:
it('should be checked after click on unchecked checkbox', () => {
const checkbox: HTMLInputElement = fixture.nativeElement.querySelector('input');
component.model = true;
fixture.detectChanges();
expect(checkbox.checked).toBeTruthy();
});
完整代码: https://stackblitz.com/edit/angular-testing-checkbox?file=app/app.component.spec.ts
推荐答案
因为角度变化检测是异步的.您的expect()
语句发生在更改检测完成之前.在测试中使用角度测试async()
函数:
Because angular change detection is asynchronous. Your expect()
statement happenned before change dectection is finished. Use angular testing async()
function in your test :
it('should be checked after click on unchecked checkbox', async( () => {
const checkbox: HTMLInputElement = fixture.nativeElement.querySelector('input');
component.model = true;
fixture.detectChanges();
fixture.whenStable().then(()=> {
expect(checkbox.checked).toBeTruthy();
})
}));
这篇关于为什么detectChanges()之后复选框选中的属性没有更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文