我想动态切换 Angular 2/Dart 组件使用的 templateUrl。
我发现解决方法是动态创建一个新组件来放置 templateUrl。有几个示例说明如何使用 Angular 2 ComponentResolver 和 TypeScript 来实现此目的,for example this one ,但我一直未能将它们转换为 Dart。
基本上我失败的是从函数传递一个新组件:
createComponentFactory(ComponentResolver resolver,
ComponentMetadata metadata) {
final cmpClass = class DynamicComponent {};
final decoratedCmp = Component(metadata)(cmpClass);
return resolver.resolveComponent(decoratedCmp);
}
此方法以及 Dart 的其他类似方法的问题在于,我无法将 class DynamicComponent {};
设置为变量或从函数返回它,而不会出现如下构建错误:
[DirectiveProcessor]:
Failed with 5 errors
Error 1: line 37, column 22 of lib/projects/project_component.dart and parts: Expected an identifier
final cmpClass = class DynamicComponent {};
^^^^^
Error 2: line 37, column 22 of lib/projects/project_component.dart and parts: Expected to find ';'
final cmpClass = class DynamicComponent {};
^^^^^
Error 3: line 37, column 22 of lib/projects/project_component.dart and parts: Expected a statement
final cmpClass = class DynamicComponent {};
^^^^^
Error 4: line 37, column 22 of lib/projects/project_component.dart and parts: Unexpected token 'class'
final cmpClass = class DynamicComponent {};
^^^^^
Error 5: line 37, column 28 of lib/projects/project_component.dart and parts: Expected to find ';'
final cmpClass = class DynamicComponent {};
^^^^^^^^^^^^^^^^
在遵循我见过的创建动态组件的任何示例时,创建这样的新组件是我常见的障碍。有谁知道如何使用 Dart 实现这一目标吗?
最佳答案
您无法在 Dart 中声明内联类。
这应该可以达到你想要的效果
class DynamicComponent {}
createComponentFactory(ComponentResolver resolver,
ComponentMetadata metadata) {
final cmpClass = DynamicComponent;
final decoratedCmp = Component(metadata)(cmpClass);
return resolver.resolveComponent(decoratedCmp);
}
如果您能让它发挥作用,我会很高兴看到完整的解决方案。
关于javascript - 如何使用 Dart 在 Angular 2 中创建动态组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37852171/