如何将 ng-template insideHTML 获取到组件

2024-06-25

我想将 ng-template 的 insideHTML 获取到我的组件。就像是

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);
  }

}

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

@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>

现场演示 https://stackblitz.com/edit/angular-k7ddsn?file=app%2Fapp.component.html

如果你的类实际上有一个模板,但你只想将 html 注入到该模板的一部分中,了解嵌入 https://scotch.io/tutorials/angular-2-transclusion-using-ng-content

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何将 ng-template insideHTML 获取到组件 的相关文章

随机推荐