Skip to content

Commit 053afba

Browse files
committed
refactor(form): host binding, cleanup, tests
1 parent 8cfa988 commit 053afba

File tree

2 files changed

+41
-10
lines changed

2 files changed

+41
-10
lines changed
Lines changed: 38 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,48 @@
1+
import { ComponentFixture, TestBed } from '@angular/core/testing';
2+
import { Component, ComponentRef, DebugElement, input } from '@angular/core';
3+
import { By } from '@angular/platform-browser';
14
import { FormDirective } from './form.directive';
2-
import { TestBed } from '@angular/core/testing';
5+
6+
@Component({
7+
imports: [FormDirective],
8+
template: '<form cForm [validated]="validated()"></form>'
9+
})
10+
class TestComponent {
11+
readonly validated = input(false);
12+
}
313

414
describe('FormDirective', () => {
15+
let component: TestComponent;
16+
let fixture: ComponentFixture<TestComponent>;
17+
let debugElement: DebugElement;
18+
let componentRef: ComponentRef<TestComponent>;
19+
20+
beforeEach(() => {
21+
TestBed.configureTestingModule({
22+
imports: [TestComponent]
23+
}).compileComponents();
24+
25+
fixture = TestBed.createComponent(TestComponent);
26+
component = fixture.componentInstance;
27+
componentRef = fixture.componentRef;
28+
debugElement = fixture.debugElement.query(By.directive(FormDirective));
29+
fixture.detectChanges();
30+
});
31+
532
it('should create an instance', () => {
633
TestBed.runInInjectionContext(() => {
734
const directive = new FormDirective();
835
expect(directive).toBeTruthy();
936
});
1037
});
38+
39+
it('should have css classes', () => {
40+
expect(debugElement.nativeElement).not.toHaveClass('was-validated');
41+
componentRef.setInput('validated', true);
42+
fixture.detectChanges();
43+
expect(debugElement.nativeElement).toHaveClass('was-validated');
44+
componentRef.setInput('validated', false);
45+
fixture.detectChanges();
46+
expect(debugElement.nativeElement).not.toHaveClass('was-validated');
47+
});
1148
});
Lines changed: 3 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,14 @@
1-
import { booleanAttribute, computed, Directive, input } from '@angular/core';
1+
import { booleanAttribute, Directive, input } from '@angular/core';
22

33
@Directive({
44
selector: 'form[cForm]',
5-
host: { '[class]': 'hostClasses()' }
5+
host: { '[class.was-validated]': 'validated()' }
66
})
77
export class FormDirective {
88
/**
99
* Mark a form as validated. If you set it `true`, all validation styles will be applied to the form. [docs]
10-
* @type boolean
10+
* @return boolean
1111
* @default false
1212
*/
1313
readonly validated = input(false, { transform: booleanAttribute });
14-
15-
readonly hostClasses = computed(() => {
16-
return {
17-
'was-validated': this.validated()
18-
} as Record<string, boolean>;
19-
});
2014
}

0 commit comments

Comments
 (0)