我想动态切换哪个templateUrl用于Angular 2 / Dart组件。
我发现可行的方法是动态创建一个新组件来放置templateUrl。有几个关于如何使用带有TypeScript的for example this one的Angular 2 ComponentResolver实现此目的的示例,但我一直未能将它们转换为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实现这个目标?
答案 0 :(得分:1)
您无法在Dart中声明内联类。
这应该做你想要的事情
class DynamicComponent {}
createComponentFactory(ComponentResolver resolver,
ComponentMetadata metadata) {
final cmpClass = DynamicComponent;
final decoratedCmp = Component(metadata)(cmpClass);
return resolver.resolveComponent(decoratedCmp);
}
如果能让它发挥作用,那么很高兴看到完整的解决方案。