【问题标题】:How to get ng-template innerHTML to component如何获取 ng-template innerHTML 到组件
【发布时间】:2017-11-10 17:12:04
【问题描述】:

我想把 ng-template 的 innerHTML 放到我的组件中。类似的东西

HTML

<my-comp [template]="myTemplate"></my-comp>
<ng-template #myTemplate></ng-template> 

TS

export class MyComponent implements OnInit {

  @Input() template: string | TemplateRef<any>;

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

}

【问题讨论】:

  • 澄清一下:你想让父组件提供的html作为子组件的模板?
  • 是的.. 如果在组件内部(使用 viewChild),我们可以获取模板。但是当模板不是组件@BeetleJuice 的一部分时如何做到这一点
  • 所以组件本身只是一个空壳,直到从外部提供模板
  • 您想将 HTML 内容作为来自另一个组件的输入发送并绑定到模板?对吗?
  • 不可能是空壳。但也许。如果这个问题解决了。它可以以多种方式使用,甚至是空壳。可以有自定义模板等等@BeetleJuice

标签: angular typescript ng-template


【解决方案1】:

由于您只需要一个用于注入模板的外壳,因此请考虑使用指令而不是组件。

@Directive({
  selector: '[template-host]'
})
export class HostDirective{

  @Input('template-host') set templateHtml(value){
    this.hostElement.innerHTML = value;
  }

  private hostElement:HTMLElement;

  constructor(elementRef:ElementRef){
    this.hostElement = elementRef.nativeElement;
  }
}

现在您可以将该指令应用于任何元素,并且提供的 template-host 绑定将导致该元素中的 html 注入。例如:

<!-- The div will contain the html in myTemplate -->
<div [template-host]="myTemplate"></div>

Live demo

如果您的班级实际上有一个模板,但您只想将 html 注入该模板的一部分,learn about transclusion

【讨论】:

  • 谢谢。但这给出了宿主元素的模板,但我想来自 ng-template
  • 我明白了。为什么不将模板存储为父组件的字符串属性?为什么要求它在父视图的 ng-template 内?
  • 所以你的意思只是一个普通的字符串?
  • @SibiRaj 是的:您在模板中编写的任何 html 字符串,都以纯字符串形式存储在类属性中。
  • 链接失效
【解决方案2】:

我今天需要解决完全相同的问题并找到了这个问题。我最终研究了 ng-bootstrap 以了解他们是如何做到的,最终这是一个相当简单的解决方案。

您需要获取要插入的字符串/模板引用的 ViewContainerRef。这可以是宿主元素(在构造函数中注入的 ViewContainerRef)或 ViewChild。例如:

constructor(private viewContainerRef: ViewContainerRef) { }

@ViewChild('someDiv', {read: ViewContainerRef}) viewContainerRef: ViewContainerRef;

接下来,在 ngOnInit() 中,您需要根据输入是 TemplateRef 还是字符串来执行 if/else 并将其分配给 viewContainerRef:

if (this.template instanceof TemplateRef) {
   this.viewContainerRef.createEmbeddedView(<TemplateRef<any>>this.template);
} else {
    this.viewContainerRef.element.nativeElement.innerHTML = this.template;
}

希望有帮助!

【讨论】:

    猜你喜欢
    • 2017-10-15
    • 1970-01-01
    • 2020-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-01
    • 1970-01-01
    • 2020-10-04
    相关资源
    最近更新 更多