![](/img/trans.png)
[英]How to make a Unit Test of an Angular Component which has a TemplateRef as Input?
[英]How to generate directive which has templateRef as Input
我有以下指令,它有一个输入; 我该如何编写它的规范文件:
import { Directive, TemplateRef } from '@angular/core';
@Directive({
selector: '[appTest]'
})
export class TestDirective {
constructor(public tpl: TemplateRef<any>) {
}
}
我试过下面一个,但它给了我一个错误:
import { TestDirective } from './test.directive';
describe('TestDirective', () => {
it('should create an instance', () => {
const directive = new TestDirective();
expect(directive).toBeTruthy();
});
});
错误new TestDirective(); 这给了我错误,因为需要默认输入。
我在<h1>test</h1>
下面试过,但没有用,我得到:
'<h1>test</h1>' is not assinable to TemplateRef<any>
您的指令没有输入。 它注入TemplateRef。 这意味着你只能这样使用它:
<ng-template appTest>
Some content of the template
</ng-template>
如果你想要一个以模板作为输入的指令,你需要这样写:
@Directive({
selector: '[appTest]'
})
export class TestDirective {
@Input() template: TemplateRef<{}>;
}
然后像这样使用它:
<div appTest [template]="tmp">...</div>
<ng-template #tmp>
Some content of the template
</ng-template>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.