我有一个基本指令作用于输入框以限制允许的最低值,在这个测试用例中不小于零。
但是,由于错误 inline template:0:0 caused by: null is not an object,我无法通过此测试。
它似乎与 ngModel 有关,但我在 YouBooks 或 FaceTubes 或 Yahoogles 的互联网上的搜索都没有得到答案。
提前感谢您的帮助。
import { Directive, Input, ElementRef, HostListener } from '@angular/core';
import { NgModel } from '@angular/forms';
@Directive({
selector: '[dleGbMinValue]',
providers: [NgModel]
})
export class MinValueDirective {
@Input('dleGbMinValue') minValue : string;
constructor(private el: ElementRef, private model: NgModel) { }
@HostListener('change') onChange() {
if (this.el.nativeElement.value && parseFloat(this.el.nativeElement.value) < parseFloat(this.minValue)) {
this.model.valueAccessor.writeValue(parseFloat(this.minValue));
this.model.viewToModelUpdate(parseFloat(this.minValue));
}
}
@HostListener('blur') onBlur() {
if (!this.el.nativeElement.value || parseFloat(this.el.nativeElement.value) < parseFloat(this.minValue)) {
this.model.valueAccessor.writeValue(parseFloat(this.minValue));
this.model.viewToModelUpdate(parseFloat(this.minValue));
}
}
}
这里是测试代码
import { MinValueDirective } from './min-value.directive';
@Component({
template: `<input type="number" dleGbMinValue="0">`
})
class TestMinValueDirectiveComponent {
}
describe('Directive: MinValueDirective', () => {
let component: TestMinValueDirectiveComponent;
let fixture: ComponentFixture<TestMinValueDirectiveComponent>;
let inputEl: DebugElement;
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [TestMinValueDirectiveComponent, MinValueDirective]
});
fixture = TestBed.createComponent(TestMinValueDirectiveComponent);
component = fixture.componentInstance;
inputEl = fixture.debugElement.query(By.css('input'));
fixture.detectChanges();
});
it('should stop at min value on change', () => {
expect(inputEl.nativeElement.value).toEqual('');
inputEl.nativeElement.value = '-5';
inputEl.triggerEventHandler('change', null);
fixture.detectChanges();
expect(inputEl.nativeElement.value).toEqual(0);
});
});
您无需在
NgModel
中提供MinValueDirective
。
使用
ngModel
中的 FormsModule
指令代替。
@Component({
template: `<input type="number" ngModel dleGbMinValue="0">` // add ngModel
})
class TestMinValueDirectiveComponent {}
不要忘记将
FormsModule
导入您的测试模块:
TestBed.configureTestingModule({
imports: [FormsModule], // here
declarations: [TestMinValueDirectiveComponent, MinValueDirective]
});
然后为了防止错误:
inline template:0:0 caused by: Cannot read property 'target' of null
从NumberValueAccessor
变
inputEl.triggerEventHandler('change', null);
到
inputEl.triggerEventHandler('change', { target: { value: '-5'}});