Issue
I have below directive which has an input; how can I write its spec file:
import { Directive, TemplateRef } from '@angular/core';
@Directive({
selector: '[appTest]'
})
export class TestDirective {
constructor(public tpl: TemplateRef<any>) {
}
}
I tried below one but it is giving me an error:
import { TestDirective } from './test.directive';
describe('TestDirective', () => {
it('should create an instance', () => {
const directive = new TestDirective();
expect(directive).toBeTruthy();
});
});
Error new TestDirective(); This is giving me error as default input is needed.
I tried below <h1>test</h1>
but is not working, I am getting:
'<h1>test</h1>' is not assinable to TemplateRef<any>
Solution
Your directive doesn’t have input. It injects TemplateRef. That means you can only use it like that:
<ng-template appTest>
Some content of the template
</ng-template>
If you want a directive with template as input, you need to write it like that:
@Directive({
selector: '[appTest]'
})
export class TestDirective {
@Input() template: TemplateRef<{}>;
}
And then use it like that:
<div appTest [template]="tmp">...</div>
<ng-template #tmp>
Some content of the template
</ng-template>