【问题标题】:Angular/typescript load component from variable从变量角度/打字稿加载组件
【发布时间】:2019-08-10 04:09:04
【问题描述】:

如何从变量加载组件? 等等我有一个数组

let arr: Array<string> = new Array('<comp1></comp1>','<comp2></comp2>');

在我的 html Temple walk 数组中,并获得组件,但只有我看到字符串为 ''

<ng-container *ngFor="let item of arr">{{item}}</ngcontainer>

感谢您的回答。

【问题讨论】:

标签: angular typescript


【解决方案1】:

你需要一个类型数组而不是字符串:

const types: ReadonlyArray<Type> = new Array(Comp1Class, Comp2Class);
<ng-container *ngFor="let componentTypeExpression of types">
  <ng-container *ngComponentOutlet="componentTypeExpression"></ng-container>
</ng-container>

请记住,它们都必须在注射器的entryComponents 中。对于惰性模块,您可以添加注入器甚至自定义模块工厂: https://angular.io/api/common/NgComponentOutlet

【讨论】:

  • 您好,感谢您的回答,但我的数组在一个服务中很深。我无法导入数组中的每个项目。如果我在 html 中简单地调用 就可以了。但我调用 *ngComponentOutlet="'ClassName'" 不起作用...
  • 这就是你在 Angular 中的做法,那时你将不得不重构你的服务,因为即使你找到了一些能满足你要求的黑魔法,它仍然是黑魔法。这是一个 Angular 库,它通过将 JS 中的 HTML 编写为字符串来以 React 方式使用模板,也许它可以帮助你:blog.angularindepth.com/…
猜你喜欢
  • 2013-08-16
  • 1970-01-01
  • 2018-11-11
  • 2020-06-22
  • 1970-01-01
  • 2018-05-01
  • 2017-03-11
  • 1970-01-01
  • 2018-12-13
相关资源
最近更新 更多