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

Car*_*hos 5 angular

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

我试过这个,但没有成功.

<template let-ref>
    <my-component [myDirective]="ref"></my-component>
</template>
Run Code Online (Sandbox Code Playgroud)

我怎么做的?

Jua*_*dán 12

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

<ng-template #templateref>
  <div>Your template content</div>
</ng-template>
Run Code Online (Sandbox Code Playgroud)

在组件中使用它@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);
  }
}
Run Code Online (Sandbox Code Playgroud)

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