【问题标题】:How to get component object from its name only如何仅从名称中获取组件对象
【发布时间】:2022-01-10 17:21:13
【问题描述】:

我有这个代码

<div>
    <wizard-step
    [component]="'ExampleComponent'"
  ></wizard-step>
</div>

ExampleComponent 是我想在组件中提取的一个组件,但是在使用组件变量时,结果是一个字符串,我想从该名称中获取 Component 对象。

感谢您的帮助。

【问题讨论】:

  • 对我来说,你想要实现的目标有点不清楚
  • 我想获取 ExampleComponent 作为组件对象而不是字符串
  • 如果你想在另一个组件模板中添加一个组件模板,请使用 angular.io/guide/content-projection

标签: html css angular typescript


【解决方案1】:

如果您想将组件作为对象引用传递给子组件,您可以使用 https://angular.io/api/core/ViewChild 在组件中检索它

@ViewChild(ExampleComponent) exampleComponent: ExampleComponent;

然后在你的模板中你会像这样传递它

<div>
  <wizard-step [component]="exampleComponent"></wizard-step>
</div>

【讨论】:

    【解决方案2】:

    对于您的问题,我想到了两个选项。您要么创建一个辅助变量,要么按照@dmance 的建议使用ng-content

    选项 1 - 辅助变量

    您需要一个辅助变量,因为 HTML 无法访问导入,因此您需要一个“代理”来访问组件

    TS

    exampleComponent: Type<ExampleComponent> = ExampleComponent;
    

    HTML

    <div>
      <wizard-step [component]="exampleComponent"></wizard-step>
    </div>
    

    选项 2 - ng-content

    内容投影很有帮助,例如,当每个组件中的内容发生变化并且您不想向组件添加大量输入时。

    HTML

    <div>
      <wizard-step>
        <example-component></example-component>
      </wizard-step>
    </div>
    

    但是你需要调整你的wizard.component.html:

    <!-- Some HTML -->
    ...
    <div>
      <ng-content></ng-content> 
      <!-- Your component is rendered here => ng-content is the anchor -->
    </div>
    ...
    <!-- SOME HTML -->
    

    如果您使用此选项,则您的 Typescript 文件中不需要 @Input。如需更多信息,请参阅docs

    【讨论】:

    • 问题是客户端会进入我无法导入或写入其类型的指定组件。有没有办法解决这个问题?
    • 那么,包含wizard-step 的组件也接收该组件作为输入?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-10-19
    • 1970-01-01
    • 2014-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-15
    相关资源
    最近更新 更多