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:
https://github.com/cdvries/angularTestApp
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;
}
--
You received this message because you are subscribed to the Google Groups
"Angular and AngularJS discussion" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To view this discussion on the web visit
https://groups.google.com/d/msgid/angular/205787f7-5f77-4520-af3e-0ee015f6e6bd%40googlegroups.com.