Reputation: 5
I want to dynamically switch which templateUrl to use for an Angular 2 / Dart component.
I've found out that the way to go would be to dynamically create a new component to place the templateUrl for. There are several examples on how to achieve this using Angular 2 ComponentResolver with TypeScript, for example this one, but I've been failing in translating them to Dart.
Basically what I fail to do is passing a new component from a function:
createComponentFactory(ComponentResolver resolver,
ComponentMetadata metadata) {
final cmpClass = class DynamicComponent {};
final decoratedCmp = Component(metadata)(cmpClass);
return resolver.resolveComponent(decoratedCmp);
}
The problem with this and other similar approaches with Dart is that I cannot set class DynamicComponent {};
to a variable or return it from a function without getting build errors like this:
[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 {};
^^^^^^^^^^^^^^^^
Creating a new component like this is the common stumbling block for me when following any of the examples I've seen for creating a dynamic component. Has anyone figured out how can you achieve this with Dart?
Upvotes: 0
Views: 473
Reputation: 657028
You can't declare classes inline in Dart.
This should do what you want
class DynamicComponent {}
createComponentFactory(ComponentResolver resolver,
ComponentMetadata metadata) {
final cmpClass = DynamicComponent;
final decoratedCmp = Component(metadata)(cmpClass);
return resolver.resolveComponent(decoratedCmp);
}
Would be nice to see the full solution if you can make it work.
Upvotes: 1