我正在为这样的模板输入创建自动聚焦指令:
import { Directive, ElementRef, AfterContentInit } from '@angular/core';
@Directive({
selector: '[appAutofocus]',
})
export class AutofocusDirective implements AfterContentInit {
constructor(private elementRef: ElementRef) {}
ngAfterContentInit() {
this.elementRef.nativeElement.focus();
}
}
我有两个问题:首先,我的自动对焦指令规范文件向我返回错误:
import { AutofocusDirective } from './autofocus.directive';
describe('AutofocusDirective', () => {
it('should create an instance', () => {
const directive = new AutofocusDirective(); //Expected 1 argument and I don't know which
expect(directive).toBeTruthy();
});
});
第二个错误是在将我的自动指令注入到我的组件的构造函数中之后,在控制台上放置了“ autofocus”指令,如下所示:
<input type="date" class="form-control" id="2-ddf"
formControlName="dtFin"appAutofocus #dtFin>
我的控制台向我返回此消息:core.js:7187错误错误:未捕获(已承诺):NullInjectorError:StaticInjectorError(AppModule)[TabPensionInvaliditeComponent-> AutofocusDirective]:
对于第一个问题:
实例化class
时,必须像以前一样传递所有非可选参数。为了正确测试directive
,我建议您看看Attribute Directive Testing guide。
第二个问题:
您可能忘记了在AutofocusDirective
中添加@NgModule#declarations
。