I have a directive which ultimately is for SMPTE timecode, so should look like 12:34:56.78, and I need it so that as the user types, it will auto format into that without the user having to put : or .
So my markup for this looks something like:
<form [formGroup]="trimOptions">
...
<input type="text" name="startTime" formControlName="startTime" timeCode />`
<input type="text" name="endTime" formControlName="endTime" timeCode />`
...
</form>
I was not sure if I should have this directive be adding ngOnChanges and ngModel to the input, it seemed simples to just use @HostListener ... So I made:
@Directive({
selector: '[timeCode]',
})
export class TimeCode {
@HostListener('keyup') onKeyUp(event: KeyboardEvent) {
console.log('keyup -', this.el.nativeElement.value);
}
}
and in the real world as I type, I see in the console:
keyup - h
keyup - he
keyup - hel
keyup - hell
keyup - hello
... In my jasmine spec, I am doing:
@Component({
template: '<input type="text" timeEntry />'
})
class TestComponent {
}
...
describe('MyDirective', () => {
let component: TestComponent;
let fixture: ComponentFixture<TestComponent>;
let input: HTMLInputElement;
beforeEach(() => {
... testbed stuff ...
fixture = TestBed.createComponent(TestComponent);
component = fixture.componentInstance;
input = fixture.debugElement.query(By.css('input')).nativeElement;
})
it('...', () => {
const str = 'hello';
for (let i = 0; i <= str.length; i++) {
let event = new KeyboardEvent('keyup', {
key: str[i],
});
input.dispatchEvent(event);
fixture.detectChanges();
});
});
When I run that test, I see my console logs, but they are:
LOG: 'keyup -', ''
LOG: 'keyup -', ''
LOG: 'keyup -', ''
LOG: 'keyup -', ''
LOG: 'keyup -', ''
For some reason the dispatched events are not adding any text to the value. I see the dispatched event has isTrusted: false on it, not sure if that has anything to do with it... So my question is, 1) why is my input's value not getting updated? and 2) is HostListener the "right" way to do what I am going to be doing (performing string replacements on the value)?