如何在angular2中获取组件的TemplateRef?

时间:2017-01-26 18:28:18

标签: angular

我有一个组件,需要将TemplateRef传递给指令,该指令将使用createEmbeddedView方法在模式中复制此组件。

我试过了,但没有成功。

<template let-ref>
    <my-component [myDirective]="ref"></my-component>
</template>

我是怎么做到的?

1 个答案:

答案 0 :(得分:10)

在模板中,在ng-template级别创建一个变量:

<ng-template #templateref>
  <div>Your template content</div>
</ng-template>

在组件中使用@ViewChild,它将可用OnInit

@Component({
  selector: 'my-component',
  templateUrl: 'my-component.html'
})
export class MyComponent implements OnInit {
  @ViewChild('templateref') public templateref: TemplateRef<any>;

  ngOnInit() {
    console.log(this.templateref);
  }
}

可能会简化ViewChild声明,我没有对它进行过多次测试。

相关问题