角度6创建TemplateRef

时间:2018-08-02 13:58:05

标签: javascript typescript testing angular6

我有(角度6)组件和TemplateRef<any>类型的输入参数

class TestComponent {
    @Input() tpl: TemplateRef<any>;
    ...
}

现在我想创建一个测试,但找不到在测试中创建模板并将其设置为输入字段的方法。

在我的HTML中,我有类似的模板

<test>
    <ng-template #tpl>
        <div>OLOLO</div>
    </ng-template>
</test>

我需要这样的东西

fixture = TestBed.createComponent(TestComponent);
component = fixture.componentInstance;
component.template = here I need instance of TemplateRef

谢谢

1 个答案:

答案 0 :(得分:1)

我不知道为什么要这样做,但是如果要访问spec文件中的模板,请使用组件中的viewchild代替输入

因此使用代码将

class TestComponent {
  @ViewChild('tpl') public tpl: ElementRef;
  ...
}

在特定条件下尝试此操作

it('should create', () => {
  console.log(component.tpl);
  expect(component).toBeTruthy();
});