Hello everyone.
Can someone please help me with this Angular custom input component? I've created a small and simple project to illustrate the problem:
This component has a onBlur event wich adds a dollar sign in front of the input when exiting the field:
import {Component, OnInit} from '@angular/core';
import {ControlValueAccessor} from '@angular/forms';
@Component({
selector: 'app-custom-input',
templateUrl: './custom-input.component.html',
styleUrls: ['./custom-input.component.css']
})
export class CustomInputComponent implements OnInit, ControlValueAccessor {
amount: any;
constructor() {
}
ngOnInit(): void {
}
onBlur($event: FocusEvent) {
console.log(JSON.stringify($event) + ':' + this.amount);
if (this.amount !== undefined) {
this.amount = this.amount.trim();
if (!this.amount.startsWith('$')) {
this.amount = '$ ' + this.amount;
}
}
}
registerOnChange(fn: any): void {
}
registerOnTouched(fn: any): void {
}
writeValue(obj: any): void {
}
}
...
<input [(ngModel)]="amount" (blur)="onBlur($event)" >
The test won't work. Any ideas what's wrong?
import {async, ComponentFixture, TestBed} from '@angular/core/testing';
import {CustomInputComponent} from './custom-input.component';
import {By} from '@angular/platform-browser';
import {Component, forwardRef} from '@angular/core';
import {FormsModule, NG_VALUE_ACCESSOR} from '@angular/forms';
describe('CustomInputComponent', () => {
let component: TestComponent;
let fixture: ComponentFixture<TestComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [FormsModule],
declarations: [TestComponent]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(TestComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
it('should add $ sign on blur', () => {
fixture.detectChanges();
component.amount = 10;
const element = fixture.debugElement.query(By.css('app-custom-input'));
element.nativeElement.dispatchEvent(new Event('blur'));
fixture.detectChanges();
fixture.whenStable()
.then(() => {
expect(component.amount).toEqual('$ 10');
});
});
});
@Component({
template: `
<form #form1='ngForm'>
<app-custom-input name="amount1" [(ngModel)]="amount"></app-custom-input>
</form>
`,
providers: [
{
provide: NG_VALUE_ACCESSOR,
multi: true,
useExisting: forwardRef(() => TestComponent),
}
]
})
class TestComponent {
amount: any;
}