简体   繁体   English

在 Angular TS 文件中返回组件选择器(Angular 2+)

[英]Return component selector inside Angular TS file (Angular 2+)

Say I have a method in my TS file that returns some html that gets injected into the template.假设我的 TS 文件中有一个方法可以返回一些被注入到模板中的 html。 I would like to include another component in the return but I cant get it to work.我想在退货中包含另一个组件,但我无法让它工作。

For example say I have the following method in my TS file:例如说我的 TS 文件中有以下方法:

returnComponent() {
   return `<my-component></my-component>`
}

Every time I run this method, it seems to only return the html tags but not the actual component.每次我运行这个方法时,它似乎只返回 html 标签,而不是实际的组件。 So after running the method I get所以在运行该方法后我得到

<div>
   <my-component>
      <!-- nothing here -->
   </my-component>
</div>

And I would like to get我想得到

<div>
   <my-component>
      <!-- the contents of 'my-component' -->
   </my-component>
</div>

What am I missing?我错过了什么? or is this not even possible?或者这甚至不可能?

What actually you are looking for is dynamic template.您实际上正在寻找的是动态模板。 You cannot put the dynamic template as string value.您不能将动态模板作为字符串值。 The template must reside inside the html of any component and you can take the reference of that template ng-template .模板必须位于任何组件的 html 内,您可以引用该模板ng-template

So you need to change your implementation.所以你需要改变你的实现。 Its not pretty simple process as you thought.它的过程并不像你想象的那么简单。

Follow this article https://medium.com/@DenysVuika/dynamic-content-in-angular-2-3c85023d9c36按照这篇文章https://medium.com/@DenysVuika/dynamic-content-in-angular-2-3c85023d9c36

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM