簡體   English   中英

如何在angular2中獲取組件的TemplateRef?

[英]How to get TemplateRef of a component in angular2?

我有一個組件,需要將您的TemplateRef傳遞給一個指令,該指令將使用createEmbeddedView方法在模式中復制此組件。

我試過這個,但沒有成功。

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

我怎么做?

在模板中創建一個 ng-template 級別的變量:

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

在組件@ViewChild它與@ViewChild一起@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聲明可以簡化,我還沒有測試過更多。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM