在Angular 6中,可以使用FormControl
的markAsDirty()
方法来更改响应式表单中的pristine
状态。下面是一个示例代码:
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { ReactiveFormsModule, FormControl } from '@angular/forms';
describe('YourComponent', () => {
let component: YourComponent;
let fixture: ComponentFixture;
let formControl: FormControl;
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [ReactiveFormsModule],
declarations: [YourComponent]
}).compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(YourComponent);
component = fixture.componentInstance;
formControl = new FormControl();
component.yourFormControl = formControl;
fixture.detectChanges();
});
it('should mark form control as dirty', () => {
expect(formControl.pristine).toBe(true);
component.changeFormControl();
expect(formControl.pristine).toBe(false);
});
});
在上面的示例中,我们使用ReactiveFormsModule
导入响应式表单模块,并创建了一个FormControl
实例。然后,我们将这个FormControl
实例分配给组件的一个变量yourFormControl
。在测试用例中,我们首先断言formControl.pristine
为true
,然后调用组件的changeFormControl()
方法,该方法在内部会调用yourFormControl.markAsDirty()
。最后,我们再次断言formControl.pristine
为false
来验证pristine
状态已经更改。
请注意,YourComponent
和changeFormControl()
是示例代码中的占位符,你需要将它们替换为你的实际组件和方法。
下一篇:Angular 6导航列表项